使用正则表达式比较两个文档

hmg*_*aly 7 python regex algorithm

我想比较两个文件而不管换行符.如果内容相同但换行符的位置和数量不同,我想将一个文档中的行映射到另一个文档中的行.

鉴于:

文件1

I went to Paris in July 15, where I met some nice people.
And I came back
to NY in Aug 15.
I am planning
to go there soon
after I finish what I do.
Run Code Online (Sandbox Code Playgroud)

文件2

I went
to Paris
in July 15,
where I met
some nice people.
And I came back to NY in Aug 15.
I am planning to go
there soon after I finish what I do.
Run Code Online (Sandbox Code Playgroud)

我想要一种算法,能够确定文档1中的第1行包含与文档2中第1行到第5行相同的文本,文档1中的第2行和第3行包含与文档2中的第6行相同的文本,等等.

1 = 1,2,3,4,5
2,3 = 6
4,5,6 = 7,8
Run Code Online (Sandbox Code Playgroud)

有没有办法使用正则表达式来匹配每个文档中的每一行,如果它跨越其他文档中的多行?

小智 0

您可以迭代 doc1 的每一行并执行如下操作:

searchstring = line.replace(' ', '[ |\n]')

然后使用此搜索字符串对 doc2 进行搜索。

match = re.search(searchstring, contents)

如果matchNULL,则没有匹配项。否则,match.group(0)将为您提供文档 2 的匹配内容。

'I went\nto Paris\nin July 15,\nwhere I met\nsome nice people.'

然后这是一个简单的练习,将其拆分为 '\n' 并找出它们来自 doc2 中的哪些行。