栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python简单文本匹配

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python简单文本匹配

当发现有匹配时返回当前的匹配行以及最后检查过的文本

from collections import deque


def serach(lines, pattern, history=5):
    prelines = deque(maxlen=history)
    for line in lines:
        if pattern in line:
            yield line, prelines
            prelines.append(line)


if __name__ == '__main__':
    i=0
    with open(r"python.txt") as f:
        for line, prelines in serach(f, "python", 5):
            for pline in prelines:
                i+=1
                print(line, end="")
                print(i)

添加简单队列:deque

找出集合中最大或者最小的N个元素:heapq,可指定长度

import heapq
nums=[1,3,324,24,123,-1,45,234,65,53]
print(heapq.nlargest(3,nums))
print(heapq.nsmallest(3,nums))

数组的排序:

import heapq
nums=[3,4,5,1,2,7,0]
heap=list(nums)
heapq.heapify(heap)
print(heap)

数组排序2:sort改变原数组,,,sorted不改变原数组

nums=[3,4,5,1,2,7,0]
nums.sort()
print(nums)
nums=[3,4,5,1,2,7,0]
nums_2=sorted(nums)
print(nums_2)
print(nums)

自定义优先级排序:

import heapq
class PriorityQueue:

    def __init__(self):
        self._queue = []
        self._index = 0

    def push(self,item,priority):
        heapq.heappush(self._queue,(-priority,self._index,item))
        self._index += 1

    def pop(self):
        return heapq.heappop(self._queue)[-1]

class Item:
    def __init__(self,name):
        self.name=name
    def __repr__(self):
        return "ITEM({!r})".format(self.name)

if __name__ == '__main__':
    q=PriorityQueue()
    q.push(Item("foo"),2)
    q.push(Item("bar"), 1)
    q.push(Item("foo"), 4)
    print(q.pop())

自定义字符段分割:re.spilt()更灵活

import re

line = "asdf ghhh; afed ,fejk, foo"
print(re.split(r"[;,s]s*,*", line))

找出以特定字符开头的文件:

import os
filenames = os.listdir(".")
print(filenames)
print([name for name in filenames if name.startswith("p")])
choices=["http","https"]
url="http:www.baidu.com"
if url.startswith(tuple(choices)):
    print(url)
else:print("no")

不区分大小写查找文本:

import re
text="UPPER PYTHON,lower python,Mixed python"
print(re.findall("python", text, re.IGNORECASE))

replace替换文本:

s="--======hello world--- n"
s2=s.replace("-", "")
print(s2.replace("=", ""))

读取txt文本文件:

with open(r"python.txt") as f:
    lines=(line.strip() for line in f)
    for line in lines:
        print(line)

文本左右对齐和添加特定字符:

text="hello world"
print("=",text.rjust(20))
print(text.ljust(20),"===")
print(text.center(20,"*"))

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/950013.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号