【问题标题】:Compare two files and remove the words from the second file Python比较两个文件并从第二个文件中删除单词 Python
【发布时间】:2020-11-27 03:43:06
【问题描述】:

对 Python 非常陌生,我正在尝试比较两个文件并使用函数获取差异。第一个文件包含英文单词 - 一个接一个(engwrds.txt),第二个文件是网络抓取文本的文本文件(ws.txt)。我想要实现的是比较这两个文件并从 ws.txt 中删除单词并将其写入另一个文件。在网络抓取的文件中有单词和句子。但在另一个文件中,单词是一个接一个地放置的。

我尝试了下面的代码,但它创建了一个空白输出文件。

with open('ws.txt', 'r', encoding='utf-8') as file1:
    with open('engwrds.txt', 'r', encoding='utf-8') as file2:
        same = set(file1).intersection(file2)

same.discard('\n')

with open('output_file.txt', 'w', encoding='utf-8') as file_out:
    for line in same:
        file_out.write(line)

然后我尝试了这个,它根本不打印任何输出。

from pathlib import Path

with open('engwrds.txt', 'r', encoding='utf-8') as fin:
    exclude = set(line.rstrip() for line in fin)

with fileinput.input('ws.txt', inplace=True) as f:
    for line in f:
        if not exclude.intersection(Path(line.rstrip()).parts):
            print(line, end='')

即使是下面的代码也不会打印任何输出。

with open('op11-Copy1.txt', 'r') as file1:
    with open('commonwords.txt', 'r') as file2:
        dif = set(file1).difference(file2)
        
dif.discard('\n')
        
with open('diff.txt', 'w') as file_out:
    for line in dif:
        file_out.write(line)

你能解释一下我在这里犯的错误吗?我提到了多个示例,例如thisthis。但我无法弄清楚这个问题。理想情况下,我想提出一个可以完成这项任务的功能。任何帮助表示赞赏!非常感谢您。

编辑:这就是 ws.txt 文件的样子。 这就是 engwrds.txt 的样子。 输出文件如下所示。

【问题讨论】:

    标签: python compare difference write


    【解决方案1】:

    只需以不同的变量打开文件并进行比较。 例如:

    假设文件 ws.txt(抓取的文件)包含:

    你的世界很美

    文件 engwrds.txt 包含这些词(一个接一个):

    世界想要狂野

    在不同的变量中打开每一个:

    with open('engwrds.txt', 'r', encoding='utf-8') as file:
        engwrds = file.read()
    
    with open('ws.txt', 'r', encoding='utf-8') as file:
        ws = file.read()
    

    从这里 engwrdsws字符串,因此您可以通过多种不同方式比较它们:

    differences = set(engwrds.split()).symmetric_difference(set(ws.split()))
    print(differences)
    
    Output: {'beautiful', 'is', 'want', 'while', 'wild', 'your'}
    

    显然,这种比较仅在您的单词用空格分隔时才有效,但从这里您将更好地了解如何解决问题。

    【讨论】:

    • 谢谢你的作品。然后我将其转换为一个函数,但它不会逐行打印。有什么想法吗?这是函数 >> def compare_files(f1,f2): with open(f1, 'r', encoding='utf-8') as f1: f1_words = f1.read() with open(f2, 'r', encoding ='utf-8') as f2: f2_words = f2.read() result1 = set(f1_words.split()).symmetric_difference(set(f2_words.split())) with open('op26.txt', 'w ', encoding='utf-8') as file: file.write(f'{result1}\n\n')
    • 我的想法不会逐行发现差异,它只是比较两个文件而不记住行的顺序。因此,如果您需要逐行比较,您可以解决 f1_words.split() 和 f2_words.split() 并将它们替换为 f1_words.split("\n") 和 f2_words.split("\n")。其中每一个都会为您提供一个列表,其中列表的每个元素都是文本文件的一行。从这里,您可以逐行比较,但剩下的问题都是您的问题(因为我们没有您的数据)
    • 当然。我添加了输入/输出文件的外观。我希望这个(op26.txt)的输出也能逐行打印。
    【解决方案2】:

    我建议你通过这个答案Compare two different files line by line in python

    想将此添加为评论,但我无法做到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多