欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python做文本按行去重的實(shí)現(xiàn)方法

 更新時(shí)間:2016年10月19日 10:33:37   作者:aaa1111sss  
每行在promotion后面包含一些數(shù)字,如果這些數(shù)字是相同的,則認(rèn)為是相同的行,對(duì)于相同的行,只保留一行。接下來通過本文給大家介紹Python做文本按行去重的實(shí)現(xiàn)方法,感興趣的朋友一起看看吧

文本:

每行在promotion后面包含一些數(shù)字,如果這些數(shù)字是相同的,則認(rèn)為是相同的行,對(duì)于相同的行,只保留一行。

思路:

根據(jù)字典和字符串切割。

建立一個(gè)空字典。

讀入文本,并對(duì)每行切割前半部分,在讀入文本的過程中循環(huán)在這個(gè)字典中查找,如果沒找到,則寫入該行到字典。否則,則表示該行已經(jīng)被寫入過字典了(即出現(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ì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論