手机
当前位置:查字典教程网 >脚本专栏 >python >Python做文本按行去重的实现方法
Python做文本按行去重的实现方法
摘要:文本:每行在promotion后面包含一些数字,如果这些数字是相同的,则认为是相同的行,对于相同的行,只保留一行。思路:根据字典和字符串切割...

文本:

每行在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)

以上所述是小编给大家介绍的Python做文本按行去重,希望对大家有所帮助,如果大家有任何疑问请给我们留言,小编会及时回复大家的。在此也非常感谢大家对查字典教程网的支持!

【Python做文本按行去重的实现方法】相关文章:

python3访问sina首页中文的处理方法

python 提取文件的小程序

python迭代器的使用方法实例

Python BeautifulSoup中文乱码问题的2种解决方法

python插入排序算法的实现代码

Python生成pdf文件的方法

Python获取脚本所在目录的正确方法

python函数返回多个值的示例方法

Python生成随机数的方法

python 多进程通信模块的简单实现

精品推荐
分类导航