Python做文本按行去重的实现方法
作者:aaa1111sss 时间:2021-12-31 17:41:07
文本:
每行在promotion后面包含一些数字,如果这些数字是相同的,则认为是相同的行,对于相同的行,只保留一行。
思路:
根据字典和字符串切割。
建立一个空字典。
读入文本,并对每行切割前半部分,在读入文本的过程中循环在这个字典中查找,如果没找到,则写入该行到字典。否则,则表示该行已经被写入过字典了(即出现重复的行了),不再写入字典,这就实现了对于重复的行只保留一行的目的。
文本如下:
/promotion/232 utm_source
/promotion/237 LandingPage/borrowExtend/? ;
/promotion/25113 LandingPage/mhd
/promotion/25113 LandingPage/mhd
/promotion/25199 com/LandingPage
/promotion/254 LandingPage/mhd/mhd4/? ;
/promotion/259 LandingPage/ydy/? ;
/promotion/25113 LandingPage/mhd
/promotion/25199 com/LandingPage
/promotion/25199 com/LandingPage
程序如下:
line_dict_uniq = dict()
with open('1.txt','r') as fd:
for line in fd:
key = line.split(' ')[0]
if key not in line_dict_uniq.values():
line_dict_uniq[key] = line
else:
continue
print line_dict_uniq
print len(line_dict_uniq)
# 这里是打印了不重复的行(重复的只打印一次),实际再把这个结果写入文件就可以了,
# 就不写这段写入文件的代码了
上面这个程序执行效率比较低,改成如下会提高一些:
line_dict_uniq = dict()
with open('1.txt','r') as fd:
for line in fd:
key = line.split(' ')[0]
if key not in line_dict_uniq.keys():
line_dict_uniq[key] = line
else:
continue
print line_dict_uniq
print len(line_dict_uniq)
继续补充一个函数
# -*- coding: utf-8 -*-
'''
只使用与较小的文件,比较大的文件运行时间长
'''
def quchong(infile,outfile):
infopen = open(infile,'r',encoding='utf-8')
outopen = open(outfile,'w',encoding='utf-8')
lines = infopen.readlines()
list_1 = []
for line in lines:
if line not in list_1:
list_1.append(line)
outopen.write(line)
infopen.close()
outopen.close()
quchong("源文件路径","目标文件路径")
以上所述是小编给大家介绍的Python做文本按行去重网站的支持!
来源:http://khaozi.blog.51cto.com/952782/1863241
标签:python,文本去重
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
asp使用 sql_dmo 给表添加索引
2010-03-17 20:57:00
浅谈用Python实现一个大数据搜索引擎
2022-05-11 19:15:52
![](https://img.aspxhome.com/file/2023/6/67326_0s.png)
PDO::inTransaction讲解
2023-06-06 08:32:27
python使用requests实现发送带文件请求功能
2023-11-03 14:23:13
激发你的灵感:50个优秀的Favicons设计
2007-10-21 19:52:00
![](https://img.aspxhome.com/file/UploadPic/200710/21/20071021211019426s.gif)
python中apply函数详情
2023-06-03 14:58:15
![](https://img.aspxhome.com/file/2023/1/87941_0s.png)
python在命令行下使用google翻译(带语音)
2023-06-02 13:47:17
我们用什么来衡量设计3:定量研究的风险
2009-07-19 14:14:00
省市级联菜单的可用性
2009-02-24 16:32:00
Python requests库用法实例详解
2021-03-31 19:36:30
VS2008 和.NET 3.5 Beta2常见问题的解决方案
2007-09-23 12:33:00
jupyter notebook清除输出方式
2021-05-08 02:51:13
![](https://img.aspxhome.com/file/2023/3/87993_0s.jpg)
用户体验中的五大要素
2008-07-07 16:41:00
mysql表的性能提升的相关问题
2010-03-03 16:31:00
JS简单实现DIV相对于浏览器固定位置不变的方法
2023-08-05 22:30:12
ThinkPHP函数详解之M方法和R方法
2023-11-22 12:00:25
Python中django学习心得
2023-12-24 17:10:15
![](https://img.aspxhome.com/file/2023/2/89322_0s.png)
神经网络(BP)算法Python实现及应用
2021-11-12 20:00:14
![](https://img.aspxhome.com/file/2023/9/98319_0s.png)
WEB设计经验-来自Microsoft
2008-05-15 07:30:00
Python装饰器用法与知识点小结
2023-11-16 00:45:02