如何在 Python 的文本文件中查找单词

How to find words in text files with Python

我是 python 的新手,我正在尝试在 python 中创建一个函数,用于查找文本文件中单词出现的行并打印行号。该函数将文本文件名和单词列表作为输入。我不知道从哪里开始。

示例

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()

目标是能够像人们在书本索引中查找单词一样在文本文件中查找单词。

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

这将 return 一个字典,其中包含给定单词的所有出现(区分大小写)。

演示

>>> 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

这样试试:

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)

闯入 Python3.7。我需要映射到一个字符串,如下所示:

for word, lines in result.items():
    print(word, ": ", ', '.join(map(str,lines)))