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

yipeiwu_com5年前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操作json文件获取内容

这篇文章主要介绍了如何基于python操作json文件获取内容,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 写case时,将case...

win10下python3.5.2和tensorflow安装环境搭建教程

win10下python3.5.2和tensorflow安装环境搭建教程

在win10环境下搭建python3.5.2和tensorflow平台,供大家参考,具体内容如下 操作步骤如下: 1、官网(https://www.python.org/ )下...

使用sklearn进行对数据标准化、归一化以及将数据还原的方法

使用sklearn进行对数据标准化、归一化以及将数据还原的方法

在对模型训练时,为了让模型尽快收敛,一件常做的事情就是对数据进行预处理。 这里通过使用sklearn.preprocess模块进行处理。 一、标准化和归一化的区别 归一化其实就是标准化的...

pyqt 实现在Widgets中显示图片和文字的方法

pyqt 实现在Widgets中显示图片和文字的方法

思路非常简单:<p>创建window,设置窗口大小,创建label1,导入图片,创建label2,导入文字,show,结束!</p> import sys...

python数值基础知识浅析

内置数据类型 Python的内置数据类型既包括数值型和布尔型之类的标量,也包括 更为复杂的列表、字典和文件等结构。 数值 Python有4种数值类型,即整数型、浮点数型、复数型和布...