如何让您的函数在文本文件中找到单词出现的行并打印相应的行号?
我必须打开带有段落的文本文件,然后我应该在段落中搜索某些单词,然后打印单词的特定行号。
这是我到目前为止所拥有的。
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
答案 0 :(得分:2)
假设您已正确打开文件,这实际上非常简单。使用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
另一个因素是列表理解,它检查任何单词是否在一行上。如果iterable的任何元素为真,则any()
函数“返回True”。以下列表理解:
[word in line for word in words]
可以理解为:
[
告诉我word
是in
line for
< sup>每个word in
所有words]
。
如果any
字在该数组中,即至少有一个单词是该行,则为真,因此将被打印。
答案 1 :(得分:2)
如果您只想测试单个字词的存在,请使用相关行的enumerate和set union:
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)
答案 2 :(得分:1)
试试这个:
words = []
lines = {}
for i in words:
lines[i] = []
with open("file", "r") as fin:
curLine = 0
for i in fin.readLines():
for j in words:
if j in i:
lines[j].append(curLine)
curLine += 1
for i in words:
print lines[j]