我是python的新手,我正在尝试在python中创建一个函数,该函数在文本文件中找到单词出现的行并打印行号。该函数将文本文件名和单词列表作为输入。我不知道从哪里开始。
实施例
index("notes.txt",["isotope","proton","electron","neutron"])
同位素1 这是我用文字制作的一些随机代码;所以,我不知道它是否能帮到我。
def index():
infile=open("test.txt", "r")
content=infile.read()
print(content)
infile.close()
目标是能够找到文本文件中的单词,就像一个人会在书的索引中找到一个单词。
答案 0 :(得分:4)
尝试这样:
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)
答案 1 :(得分:3)
words = ['isotope', 'proton', 'electron', 'neutron']
def line_numbers(file_path, word_list):
with open(file_path, 'r') as f:
results = {word:[] for word in word_list}
for num, line in enumerate(f, start=1):
for word in word_list:
if word in line:
results[word].append(num)
return results
这将返回一个字典,其中包含所有出现的给定单词(区分大小写)。
样本
>>> words = ['isotope', 'proton', 'electron', 'neutron']
>>> result = line_numbers(file_path, words)
>>> for word, lines in result.items():
print(word, ": ", ', '.join(lines))
# in your example, this would output:
isotope 1
proton 3
electron 2
neutron 5
答案 2 :(得分:0)
Adam Smith's answer在Python3.7中破解。我需要映射到一个字符串,如下所示:
for word, lines in result.items():
print(word, ": ", ', '.join(map(str,lines)))