如何让函数在文本文件中找到单词出现的行并打印相应的行号?
我不得不打开一个包含该段落的文本文件,然后我应该在该段落中搜索某些单词,然后打印这些单词的特定行号。
这是我目前所拥有的。
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
假设您已正确打开文件,这实际上很容易。使用 file.read() 将整个文件拉入,这是您不想要的。 If you are doing line-based processing, iterate through the file using with
因为它使文件的打开、关闭和错误处理变得更加容易:
with open(filename) as file:
for line in file:
#do something
您逻辑的核心部分是 enumerate()
,它接受一个可迭代对象并返回一个计数以及每个迭代项目。
words = ["word","another"]
for line_num,line in enumerate(file):
if any([word in line for word in words]):
print line_num, line
另一个因素是列表理解,它检查任何单词是否在一行上。 any()
函数“如果可迭代的任何元素为真,则返回真”。以及以下列表理解:
[word in line for word in words]
可以读作:
[
tell me if word
is in
the line for
each word in
all of the words]
.
如果 any
单词在该数组中,即至少有一个单词是该行,则它为真,因此将被打印。
我是一名优秀的程序员,十分优秀!