下面是一种解决问题的方法:
import re
import os.path
def findWord(filename:str, word:str):
if not os.path.isfile(filename):
print("File not found")
return
with open(filename, 'r') as f:
fStr = str(f.read())
locs = []
loc = 0
while loc != -1:
loc = fStr.find(word, locs[-1] + len(word) if locs else 0)
if loc != -1:
locs.append(loc)
print(locs)
findWord('foo.txt', 'foo')
输入文件foo。txt文件:
barbarfoobarbarbarfoobarbarbarfoobar
barbarfoobarbarbarfoobarbarbarfoobar
barbarfoobarbarbarfoobarbarbarfoobar
barbarfoobarbarbarfoobarbarbarfoobar
barbarfoobarbarbarfoobarbarbarfoobar
barbarfoobarbarbarfoobarbarbarfoobar
输出:
[6, 18, 30, 43, 55, 67, 80, 92, 104, 117, 129, 141, 154, 166, 178, 191, 203, 215]