如何搜索字符串并找到字符串所在的行号?
例如
>>> findlinenb('example.txt', ['desktop', 'connection', 'processor'])
desktop in 23
connection in 35, 38, 35
processor in 4, 5, 6, 8
我的代码:
def findlinenb (filename, list):
file = open(filename, "r")
content = file.read()
for i in list:
if content.find(i):
print (i, "in", content.count('\n') + 1)
非常感谢任何想法或建议。
彼得
答案 0 :(得分:0)
words = ['desktop', 'connection', 'processor']
occurrences = dict((w, []) for w in words)
with open("example.txt") as f:
for i, line in enumerate(f, 1):
for w in words:
if w in line:
occurrences[w].append(i)
print occurrences.items()