我是 python 的新手,正在尝试在 python 中创建一个函数,该函数查找文本文件中出现单词的行并打印行号。该函数将文本文件名和单词列表作为输入。我不知道从哪里开始。
例子
index("notes.txt",["isotope","proton","electron","neutron"])
Run Code Online (Sandbox Code Playgroud)
同位素 1
质子 3
电子 2
中子 5
这是我用文本制作的一些随机代码;所以,我不知道它是否可以帮助我。
def index():
infile=open("test.txt", "r")
content=infile.read()
print(content)
infile.close()
Run Code Online (Sandbox Code Playgroud)
目标是能够在文本文件中找到单词,就像人们在书的索引中查找单词一样。
试试这样:
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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
29987 次 |
最近记录: |