【发布时间】:2018-10-31 01:58:51
【问题描述】:
我想删除几乎相同的重复项,但只保留最长的一个。我正在考虑首先比较第一个单词或前几个单词以过滤掉候选进行比较。然后比较剩余元素的长度。如果它是最长的,我会将它写入一个新的文本文件。 这里是测试文件https://drive.google.com/file/d/1tdewlNtIqBMaldgrUr02kbCKDyndXbSQ/view?usp=sharing
输入
I am Harry.
I am Harry. I like
I am Harry. I like to eat apple.
I am Garry.
I am Garry. I am Hap
I am Garry. I am Happy.
输出
I am Harry. I like to eat apple.
I am Garry. I am Happy.
我正在用 Python 做这件事,但它就是行不通。
代码
f1 = open('a.txt','r') # Read from file
ListofLine = f1.readlines() # Read the line into list
f2 = open('n.txt','w') # Open new file to write
# Iterate all the sentences to compare
for x in len(ListofLine):
# Comparing first word of the sentences
if(ListofLine[x].split()[0] = ListofLine[x+1].split()[0]):
# Comparing the length and keep the longest length sentences
if(len(ListofLine[x])>len(ListofLine[x+1])):
f2.write(ListofLine[x])
f1.close()
f2.close()
【问题讨论】:
-
试试我的解决方案:jdoodle.com/embed/v0/vIG
-
我已经用测试文件尝试了所有解决方案,但有些文本会丢失。我想知道为什么。看起来消除的太多了。
-
你能在这里提供输入文件吗?
-
只重复最后两句。但是我尝试了代码,它会消除太多。
标签: python text duplicates