Python做文本按行去重的实现方法

yipeiwu_com6年前Python基础

文本:

每行在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做文本按行去重,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

Python 转义字符详细介绍

Python 转义字符 在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符。如下表: 原始字符串 有时我们并不想让转义字符生效,我们只想显示字符串原来的意思,这就要用r和...

Python 将json序列化后的字符串转换成字典(推荐)

一般而言下面的就可以完成需求了。 def convertToDic(data): jsonDic=json.loads(data) return dict(jsonDic) 但...

Python3使用PyQt5制作简单的画板/手写板实例

Python3使用PyQt5制作简单的画板/手写板实例

1.前言 版本:Python3.6.1 + PyQt5 写一个程序的时候需要用到画板/手写板,只需要最简单的那种。原以为网上到处都是,结果找了好几天,都没有找到想要的结果。 网上的要么是...

python面向对象_详谈类的继承与方法的重载

python面向对象_详谈类的继承与方法的重载

1. 类的继承与方法的重载 上面就是先定义了一个类A,然后由定义了一个类B,B继承了类A,这样B就有了A的非私有属性和方法。 class Washer: company='...

在Python中用keys()方法返回字典键的教程

 keys()方法返回在字典中的所有可用的键的列表。 语法 以下是keys()方法的语法: dict.keys() 参数    ...