python文本去重_Python做文本按行去重的实现方法
文本:
每行在promotion后面包含一些數(shù)字,如果這些數(shù)字是相同的,則認(rèn)為是相同的行,對(duì)于相同的行,只保留一行。
思路:
根據(jù)字典和字符串切割。
建立一個(gè)空字典。
讀入文本,并對(duì)每行切割前半部分,在讀入文本的過(guò)程中循環(huán)在這個(gè)字典中查找,如果沒找到,則寫入該行到字典。否則,則表示該行已經(jīng)被寫入過(guò)字典了(即出現(xiàn)重復(fù)的行了),不再寫入字典,這就實(shí)現(xiàn)了對(duì)于重復(fù)的行只保留一行的目的。
文本如下:
/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)
# 這里是打印了不重復(fù)的行(重復(fù)的只打印一次),實(shí)際再把這個(gè)結(jié)果寫入文件就可以了,
# 就不寫這段寫入文件的代碼了
上面這個(gè)程序執(zhí)行效率比較低,改成如下會(huì)提高一些:
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)
繼續(xù)補(bǔ)充一個(gè)函數(shù)
# -*- coding: utf-8 -*-
'''
只使用與較小的文件,比較大的文件運(yùn)行時(shí)間長(zhǎng)
'''
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("源文件路徑","目標(biāo)文件路徑")
以上所述是小編給大家介紹的Python做文本按行去重,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)我們網(wǎng)站的支持!
本文標(biāo)題: Python做文本按行去重的實(shí)現(xiàn)方法
本文地址: http://www.cppcns.com/jiaoben/python/166891.html
總結(jié)
以上是生活随笔為你收集整理的python文本去重_Python做文本按行去重的实现方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python中lambda函数_pyth
- 下一篇: python nltk lemmatiz