【问题标题】:Find phrases from one text file in another text file with python使用python从另一个文本文件中的一个文本文件中查找短语
【发布时间】:2015-07-08 21:06:51
【问题描述】:

我有一个文件,它是一个短语列表,每行一个短语。 另一个文件没有以任何方式分隔,它只是一个巨大的文字文件。我想在第二个文件中搜索短语,如果找到,则打印该短语。这是我目前的代码。

f = open("phrase.txt", "r")
g = open("text.txt", "r")

for line in f:
    search=line.lower()


for word in g:
    if search in word:
        print(search)

不过,这并没有为我打印任何东西。

编辑:我将代码更改为:

f = open('phrase.txt').readlines()
f = [f.strip('\n').lower() for f in f]
g = open('text.txt').read()
for phrase in f:
    if phrase in g:
        print (phrase)

现在我得到了匹配的短语。但是,有些短语后面有破折号 (-) 和更多字母,即使破折号之前的短语出现在 text.txt 中,程序也不会拾取它们。有什么办法可以改变吗?

【问题讨论】:

  • 试试:f = open("phrase.txt", "r").read() or f = open("phrase.txt", "r").readlines()
  • 好的,我做了 .read() 并且它实际上只是打印了字母 e 而没有其他任何东西......知道为什么会这样吗?.readlines() 也没有返回任何内容
  • “text.txt”中的单词之间有空格吗?
  • 是的,有空格,但所有单词都在一行

标签: python


【解决方案1】:

如果要搜索文件中的每个短语,则必须嵌套循环,目前,您只搜索最后一个短语

phrases = open("phrase.txt").readLines()

for phrase in phrases:
    search= phrase.lower()
    words = open("text.txt", "r")
    for word in words:
        if search in word:
            print(search)
    words.close()

但是,现在事情开始看起来很有趣,因为您在询问一个词组是否包含在一个单词中,这看起来不正确。所以

phrases = open("phrase.txt").readLines()
words = open("text.txt").read()

for phrase in phrases:
    all_words_found = True
    phrase_words = phrase.lower().split(" ")
    for word in phrase_words:
        if word not in words:
            all_words_found = False
            break

    if all_words_found:
        print phrase

这就是你想要的,我确实相信

【讨论】:

  • 啊,是的,你是对的。虽然我运行了这段代码,但它也没有返回任何内容
  • 我最近编辑了它。现在就试试。我没有时间实际测试它
  • 是的,仍然没有!我将一些我知道存在于 text.txt 中的单词放入了 phrase.txt 中,但仍然没有:(
  • 使用此算法,短语本身必须在 text.txt 中以短语出现的确切形式出现。短语的单词不能分散在整个 text.txt
  • 是的,它只是找不到短语,即使它们是准确的。它不会打印任何内容
【解决方案2】:
f = open('phrase.txt').readlines()
f = [f.strip('\n').lower() for f in f]
g = open('text.txt').read()
words = g.split()

for phrase in f:
    search_words = phrase.split()
    for word in search_words:
        if word in words:
            print phrase

【讨论】:

  • @nat,我把你的变量名改了一点,但试试看。
  • 谢谢!这有效,但它只返回单词而不是完整的短语。
  • 我改了,但我不知道如何在 cmets 中发布代码
  • 试试修改后的。我不确定你的输出应该是什么,但也许可以做到。
  • 这段代码不完全正确,它只检查短语中的一个单词是否在text.txt中,但可以轻松修改
猜你喜欢
  • 1970-01-01
  • 2013-02-26
  • 2021-11-01
  • 2018-03-29
  • 2019-03-06
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
  • 2023-01-23
相关资源
最近更新 更多