python - 几乎相同的副本,只是长度不同
问题描述
我想删除几乎相同的重复项,但只保留最长的一个。我正在考虑首先比较第一个单词或前几个单词以过滤掉候选进行比较。然后比较剩余元素的长度。如果它是最长的,我会将它写入一个新的文本文件。这是测试文件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()
解决方案
您需要定义一个标准才能找到您所谓的公共部分。它可以是第一句话,例如“我是哈利”。</p>
要解析句子,您可以使用 RegEx,例如:
import re
# match a sentence finishing by a dot
re_sentence = r'((?:(?!\.|$).)+\.?)\s*'
find_all_sentences = re.compile(re_sentence, flags=re.DOTALL).findall
这里find_all_sentences是一个函数。它是re.compile
findall函数的结果。它是查找一行中所有句子的助手。
一旦定义了这个函数,你就可以用它来解析行并提取第一个句子,这被认为是要检查的公共部分。
任何时候你匹配一个句子,你都可以将它存储在一个字典中(这里我使用了一个OrdererdDict来保持行的顺序)。当然,如果你发现更长的行,你可以用这个替换现有的行:
import collections
lines = [
"I am Harry. I like to eat apple",
"I am Harry.",
"I am Garry.",
"I am Garry. I am Happy."]
longuest = collections.OrderedDict()
for line in lines:
sentences = find_all_sentences(line)
first = sentences[0]
if first in longuest:
longuest[first] = max([longuest[first], line], key=lambda l: len(l))
else:
longuest[first] = line
最后,您可以将结果序列化到文件中。或打印:
for line in longuest.values():
print(line)
要写入文件,请使用with语句:
import io
out_path = 'path/to/sentences.txt'
with io.open(out_path, mode='w', encoding='utf-8') as f:
for line in longuest.values():
print(line, file=f)
推荐阅读
- flutter - 列表中的控制台打印值详细信息
- unity3d - HoloLens:如何在远距离稳定全息图
- angular - 订阅 Observable 并获取特定类型的事件
- elasticsearch - 具有多个术语查询的 Elasticsearch nester_filter
- jpa - 是否有可能检查一个实体的多个列是否包含 JPA 中的一个搜索键
- python - cython中不同字符串的相同内存地址
- node.js - Docker MACVLAN 端口未正确映射
- eclipse - 如何更改具有显着偏差的分支?
- javascript - 高效地使用 map 函数渲染许多 React 组件
- intellij-idea - 如何为 IntelliJ 制作简单的计算器语法高亮显示?