我是 python 新手,正在尝试在 python 中创建一个函数,该函数查找文本文件中出现该单词的行并打印行号。该函数将文本文件名和单词列表作为输入。我不知道从哪里开始。
Example
index("notes.txt",["isotope","proton","electron","neutron"])
同位素1
质子3
电子2
中子5
这是我用文本编写的一些随机代码;所以,我不知道它是否可以帮助我。
def index():
infile=open("test.txt", "r")
content=infile.read()
print(content)
infile.close()
目标是能够像在书籍索引中查找单词一样在文本文件中查找单词。
尝试这样:
def word_find(line,words):
return list(set(line.strip().split()) & set(words))
def main(file,words):
with open('file') as f:
for i,x in enumerate(f, start=1):
common = word_find(x,words)
if common:
print i, "".join(common)
if __name__ == '__main__':
main('file', words)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)