搜索字符串并查找字符串所在的行号[PYTHON]
如何搜索字符串并找到字符串所在的行号 比如说搜索字符串并查找字符串所在的行号[PYTHON],python,Python,如何搜索字符串并找到字符串所在的行号 比如说 >>> 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.rea
>>> 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)
非常感谢您的任何想法或建议
PeterSimply
grep-n“your_string”your_file.txt
感谢您的快速回复。
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()