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: ソートすると元の配列が変更されます、、、ソートしても元の配列は変更されません

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,"*"))
#居中对齐^,左对齐<,居中对齐…^
print(format(text,"=^20s"))
#自定义格式对齐
print('{:>10s} {:>10s}'.format("hello", "world"))

小数点以下 2 桁までにしてください。

x=1.2645
print(format(x, ".2f"))

文字列のマージ:

part=["wo","shi","bobo"]
# " ,"中可以放任意符号
x=" ".join(part)
print(x)

カスタム文字列の連結: 形式

a="wo shi"
b="bobo"
print(a+" "+b)
print("{} {}".format(a,b))

データを文字列に変換するときに、反復子を使用して連結を完了します。

data=["acme",50,91]
print("".join([str(i) for i in data]))

ランダムの使用:

シーケンスから要素をランダムに選択します。

values=[2,3,4,1,5,2,1,78]
import random

print(random.choice(values))
print(random.sample(values, 3))
#原地洗牌
random.shuffle(values)
print(values)

#随机数:
print(random.randint(0, 100))

##0--1之间的浮点随机数
print(random.random())

基本的な時間変換: datatime timedelta

from datetime import timedelta
a=timedelta(days=2,hours=6)
b=timedelta(hours=4)
c=a+b
print(c.days)
print(c.seconds)

おすすめ

転載: blog.csdn.net/weixin_42435798/article/details/125126049