【问题标题】:How to find words that are not the same between two text files如何在两个文本文件之间查找不相同的单词
【发布时间】:2016-01-27 12:26:45
【问题描述】:

我有两个文本文档,它们基本上包含所有相同的单词,但也有一些例外。如何在 document2 中找到 document1 中没有的单词并将它们打印出来?例如:

文档1: “你好,你好吗”

文档2: “嗨,约翰,你今天好吗”

期望的输出: “今天你好,约翰”

编辑:我想打印仅存在于 document2 中且在 document1 中任何地方都找不到的单词。我不想打印它们之间相同的单词。

我创建了这段代码,我认为它可以在两个文本文件之间找到匹配项,这并不是我真正想要的:

doc1 = open("K:\System Files\Desktop\document1.txt", "r+")
doc2 = open("K:\System Files\Desktop\document2.txt", "r+")

list1 = []
list2 = []

for i in doc1: #Removes the new line after each word
    i = i[:-1]
    list1.append(i)
for i in doc2:
    i = i[:-1]
    list2.append(i)

for i in list1:
    for j in list2:
        if i == j:
            print(i)

【问题讨论】:

  • 文档 1 有 138 个单词,文档 2 有 187 个单词——每个单词都换行,因为它是一个列表。我一般是编程新手,所以我还没有走得很远,但我想我能够创建代码来打印两个文件之间匹配的单词(我将编辑我的原始帖子,以便您看到它) .现在我想找到一种方法来打印只存在于document2中而不是document1中任何地方的单词。
  • 我建议您在两条路径中添加 r 前缀,例如r"K:\System....txt" 避免反斜杠出现问题。

标签: python


【解决方案1】:

如果您不担心单词的顺序,那么您可以使用集合来完成此操作,如下所示:

import re

def get_words(filename):
    with open(filename, 'r') as f_input:
        return set(w.lower() for w in re.findall(r'(\w+)', f_input.read()))

words1 = get_words('document1.txt')
words2 = get_words('document2.txt')

print words2 - words1

这将显示:

set(['john', 'hi', 'today'])

在两组上使用- 具有在两组之间为您提供difference 的效果。

【讨论】:

    猜你喜欢
    • 2013-04-29
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    相关资源
    最近更新 更多