日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

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

發(fā)布時(shí)間:2024/9/18 python 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python文本去重_Python做文本按行去重的实现方法 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文本:

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

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。