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

时间:2018-11-05 15:42:17

标签: python text

我有两个文本文件,我想根据两个原始文本文件中每一行是否有相同的部分来写出两个新的文本文件。

文本文件的格式如下:

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)

但是我不确定这是否适合我需要分开的情况。有什么办法可以做到的吗?

谢谢

2 个答案:

答案 0 :(得分:0)

可能会有更短的解决方案,但这应该可行

PCT_IDX = _  # find which index of line.split() corresponds to potentiallycommontext

def lines(filename):
    with open(filename, 'r') as file:
        for line in file:
            line = line.rstrip('\n')
            yield line

lines_1 = lines('some_file_1.txt')
lines_2 = lines('some_file_2.txt')
with open('some_output_file.txt', 'w') as file_out:
    for (line_1, line_2) in zip(lines_1, lines_2):
        maybe_cmn1 = line_1.split()[PCT_IDX]
        maybe_cmn2 = line_2.split()[PCT_IDX]
        if maybe_cmn1 == maybe_cmn2:
            file_out.write(line_1)
            file_out.write(line_2)

答案 1 :(得分:0)

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

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)