【问题标题】:How to find words in text files with Python如何使用 Python 在文本文件中查找单词
【发布时间】:2015-03-10 22:22:40
【问题描述】:

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

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

【问题讨论】:

  • grep 有什么问题?
  • 如果这是一个 dup,或者有其他问题,那不应该在 cmets 中 - 否则应该如何学习....
  • 一个单词出现在多行怎么办?
  • 我希望能够发布该单词出现的所有行。

标签: python text


【解决方案1】:
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】:

    试试这样:

    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)
    

    【讨论】:

    • 看起来人们只是对所有答案投了反对票,因为这是一个公认的格式不正确的问题。我本来想找一个完全一样的骗子,但我找不到任何要求匹配单词列表的东西。
    • 很抱歉没有更好地表达我的问题。我正在社区大学上 Python 课,这是作业。我已经研究了几天,但我无法弄清楚。赋值说明该函数将文本文件名和单词列表作为输入。我没有对任何人投反对票。无论如何,谢谢大家的回答!
    【解决方案3】:

    Adam Smith's answer 在 Python3.7 中中断。我需要按如下方式映射到一个字符串:

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

    【讨论】:

      猜你喜欢
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2017-11-14
      相关资源
      最近更新 更多