2011-11-14 39 views
0

如何搜索字符串並找到字符串所在的行號?搜索字符串並找到字符串位於[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.read() 
for i in list: 
    if content.find(i): 
     print (i, "in", content.count('\n') + 1) 

任何意見或建議是極大的讚賞。

彼得

+0

簡單'grep的-n 「your_string」 your_file.txt' – wim

回答

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() 
+0

謝謝你的快速反應。 – user1044730

+0

@ user1044730:原代碼有一個bug - 現在已經修復。 –

相關問題