搜索文本文件并打印行号 [英] Searching a text file and printing line numbers
本文介绍了搜索文本文件并打印行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取函数以在文本文件中找到单词所在的行并打印相应的行号?
How do you get your function to find the lines in the text file where the word occurs and print the corresponding line numbers?
我必须打开一个带有段落的文本文件,然后应该在段落中搜索某些单词,然后为这些单词打印特定的行号.
I had to open a text file with the paragraph and then am supposed to search the paragraph for certain words and then print the specific line numbers for the words.
这是我到目前为止所拥有的.
Here is what I have so far.
words = [network, devices, computer, fire, local, area, room, single]
def index(string):
lines = open('Network.txt', 'r')
string = str(lines.read())
lines.close()
return string
推荐答案
使用枚举和相关行的设置并集如果您只想测试单个单词的存在,则:
Use enumerate and a set union of the line in question if you just want to test for presence of individual words:
words={'some', 'target', 'words', 'in', 'a', 'set'}
with open(f_name) as fin:
for line_num, line in enuemrate(fin):
if set(line.split()) & words:
print(line_num, line)
这篇关于搜索文本文件并打印行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文