python - 根据文本文件的单个部分比较两个文本文件中的两行

标签 python text

我有两个文本文件,我想根据两个原始文本文件中的每一行是否有公共(public)部分写出两个新的文本文件。

文本文件的格式如下:

commontextinallcases   uniquetext2   potentiallycommontext    uniquetext4

虽然有超过 4 列,但您已经明白了。我想检查每个文本文件中的“潜在通用文本”部分,如果它们相同,则将每个文本文件的整行写到一个新的文本文件中,每个文件都有自己独特的文本。

在读入它时只需使用 .split() 命令即可将其拆分相当容易。我找到了以下代码:

with open('some_file_1.txt', 'r') as file1:
with open('some_file_2.txt', 'r') as file2:
    same = set(file1).intersection(file2)

same.discard('\n')

with open('some_output_file.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)

但我不确定这是否适用于我需要分割线的情况。有没有办法做到我所缺少的?

谢谢

最佳答案

我认为这种设置方法不适合您的情况。
我会尝试像

with open('some_file_1.txt', 'r') as file1, open('some_file_2.txt', 'r') as file2, open('some_output_file.txt', 'w') as file_out:
    for line1, line2 in zip(file1, file2):
        if line1.split()[2] == line2.split()[2]:
            file_out.write(line1)
            file_out.write(line2)

关于python - 根据文本文件的单个部分比较两个文本文件中的两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53157565/

相关文章:

Python 除法舍入

python - 如何使用 BeautifulSoup 从 html 中提取元素

python - 如何在 tkinter 的文本小部件中停止复制、粘贴和退格?

python - NumPy 数据类型不理解

javascript - Flask 和 Angular Web 应用程序路由

python - 破解 Jinja2 以从 `utf-8` 而不是 `ascii` 编码?

vba - 使用 VBA 更改 PowerPoint 演示文稿中的默认文本方向

css - 页脚文字无法 move

java - Java 中有没有内置的方法来打印样式文本?

javascript - 无法将文本转换为 JavaScript 数组