繁体   English   中英

如何使用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()

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

尝试这样:

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

Adam Smith的答案在Python3.7中中断。 我需要映射到一个字符串,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM