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

2024-06-01 12:07:40 发布

您现在位置: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()

目标是能够在文本文件中找到单词,就像一个人在一本书的索引中找到一个单词一样。


Tags: 函数txt示例列表indexcontent单词infile
2条回答

这样试试:

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

相关问题 更多 >