【发布时间】:2022-12-11 08:57:39
【问题描述】:
伙计们,这是我的代码:
import io
import difflib
import re
with io.open('textest.txt', mode="r", encoding="utf_8_sig") as file:
lines1 = file.readlines()
with io.open('minitext.txt', mode="r", encoding="utf_8_sig") as file:
lines2 = file.readlines()
def prefilter(line):
return re.sub("\s+"," ",line.strip())
for d in difflib.ndiff([prefilter(x) for x in lines1],[prefilter(x) for x in lines2]):
print(d)
textest.txt 是完整的歌曲,minitext.txt 只是其中的一部分。输出是这样的(我知道,这是一首贾斯汀比伯的歌,这只是一个例子)
+ somethin' I don't wanna hold back
- For all the times that you rained on my parade
- And all the clubs you get in using my name
- You think you broke my heart, oh, girl, for goodness' sake
- You think I'm crying on my own, well, I ain't
- And I didn't wanna write a song
- 'Cause I didn't want anyone thinkin' I still care, I don't, but
- You still hit my phone up
- And baby, I'll be movin' on
- And I think you should be somethin' I don't wanna hold back
Maybe you should know that
My mama don't like you and she likes everyone
And I never like to admit that I was wrong
And I've been so caught up in my job
Didn't see what's going on, but now I know
+
+
+
I'm better sleeping on my own
+ 'Cause if you like the wa
- 'Cause if you like the way you look that much
- Oh, baby, you should go and love yourself
- And if you think that I'm still holdin' on to somethin'
问题是:我只想打印 +(lines2 上的不同行,即 minitext.txt),以及不同的行号。我还想忽略完全空行,所以输出就像:
- 有些事情我不想阻止(minitext.txt 中的行数)
- '因为如果你喜欢 wa(minitext.txt 中的行数)
或类似的东西。有什么办法可以做到吗?
【问题讨论】:
标签: python regex python-re txt difflib