实时监测文件内容的变化,每当有新一行数据写入文件后,分析该行是否包含有要寻找的关键词,若有,则触发。
import time
from fuzzywuzzy import fuzz
KEY = r'要寻找的关键词'
threshold = 90
if __name__ == '__main__':
path = r'sample.txt'
file = open(path)
# 将每次从文件最后一行开始读
# 如果没有这一行,就会每次启动程序后从文件最开始地方读
file.seek(0, 2)
while True:
where = file.tell()
line = file.readline()
if not line:
time.sleep(1)
file.seek(where)
else:
pr = fuzz.partial_ratio(line, KEY)
if pr > threshold:
print(line)