Python比较相似或相等行的文本文件

时间:2018-01-17 21:40:47

标签: python sequencematcher

我有2个文本文件,我的目标是找到文件First.txt中不在Second.txt中的行,并将所述行输出到第三个文本文件Missing.txt,我完成了:

fn = "Missing.txt"
try:
    fileOutPut = open(fn, 'w')
except IOError:
    fileOutPut = open(fn, 'w')
fileOutPut.truncate()
filePrimary = open('First.txt', 'r', encoding='utf-8', errors='ignore')
fileSecondary = open('Second.txt', 'r', encoding='utf-8', errors='ignore')
bLines = set([thing.strip() for thing in fileSecondary.readlines()])
for line in filePrimary:
    line = line.strip()
    if line in bLines:
        continue
    else:
        fileOutPut.write(line)
        fileOutPut.write('\n')
fileOutPut.close()
filePrimary.close()
fileSecondary.close()

但是在运行脚本之后我遇到了问题,有些行非常相似,例如:

[PR] Zero One Two Three ft Four

和(括号后面没有空格)

[PR]Zero One Two Three ft Four

[PR] Zero One Two Three ft Four

和(大写F字母)

[PR] Zero One Two Three Ft Four

我找到了SequenceMatcher,它可以满足我的要求,但我如何在比较中实现这一点,因为它们不仅仅是两个字符串,而是一个字符串和一个集合

1 个答案:

答案 0 :(得分:0)

IIUC,即使空格或大小写不同,也要匹配行。

执行此操作的一种简单方法是删除空格,并在阅读中将所有内容都设为相同的情况:

import re

def format_line(line):
    return re.sub("\s+", "", line.strip()).lower()

filePrimary = open('First.txt', 'r', encoding='utf-8', errors='ignore')
fileSecondary = open('Second.txt', 'r', encoding='utf-8', errors='ignore')
bLines = set([format_line(thing) for thing in fileSecondary.readlines()])
for line in filePrimary:
    fline = format_line(line)
    if fline in bLines:
        continue
    else:
        fileOutPut.write(line + '\n')

更新1 :模糊匹配

如果您想模糊匹配,可以执行nltk.metrics.distance.edit_distancedocs)之类的操作  但你无法将每一行与每一行进行比较(最坏的情况)。你失去了in操作的速度。

例如

from nltk.metrics.distance import edit_distance as dist

threshold = 3  # the maximum number of edits between lines

for line in filePrimary:
    fline = format_line(line)
    match_found = any([dist(fline, other_line) < threshold for other_line in bLines])

    if not match_found:
        fileOutPut.write(line + '\n')