在文本文件filename 中,查找由系统剪切板(pyperclip)复制的关键词keyWord,并显示从offsetMin 到offsetMax 行的信息。
import pyperclip
import os,sys
filename = r'D:xxx.txt'
offsetMin = -1
offsetMax = 5
def findSth():
file=open(filename,'r')
file_contents=file.readlines()#按行读取全部内容
maxCnt = len(file_contents)
try:
while True:
print(f"search:{pyperclip.waitForNewPaste(999)}")
os.system ('cls')
keyWord = pyperclip.paste()
if keyWord == ''or keyWord == '\n': continue
lineCnt = 0 # 计算行数
for content in file_contents:
if keyWord in content:
print("")
for j in range(offsetMax-offsetMin):
idx = lineCnt+offsetMin+j
if idx<0 : idx = 0
if idx>maxCnt:idx =maxCnt
print(file_contents[idx],end=' ')
lineCnt += 1
#raise Exception("抛出一个异常")
except Exception as e:##EOFError
os.system ('cls')
finally:
file.close()
if __name__=='__main__':
while True:
findSth()