Python做文本按行去重的實(shí)現(xiàn)方法
文本:
每行在promotion后面包含一些數(shù)字,如果這些數(shù)字是相同的,則認(rèn)為是相同的行,對于相同的行,只保留一行。
思路:
根據(jù)字典和字符串切割。
建立一個空字典。
讀入文本,并對每行切割前半部分,在讀入文本的過程中循環(huán)在這個字典中查找,如果沒找到,則寫入該行到字典。否則,則表示該行已經(jīng)被寫入過字典了(即出現(xiàn)重復(fù)的行了),不再寫入字典,這就實(shí)現(xiàn)了對于重復(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í)際再把這個結(jié)果寫入文件就可以了,
# 就不寫這段寫入文件的代碼了
上面這個程序執(zhí)行效率比較低,改成如下會提高一些:
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ǔ)充一個函數(shù)
# -*- coding: utf-8 -*-
'''
只使用與較小的文件,比較大的文件運(yùn)行時間長
'''
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做文本按行去重,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Python實(shí)現(xiàn)html轉(zhuǎn)png的完美方案介紹
這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)html轉(zhuǎn)png功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-03-03
Python實(shí)現(xiàn)的檢測網(wǎng)站掛馬程序
這篇文章主要介紹了Python實(shí)現(xiàn)的檢測網(wǎng)站掛馬程序,需要的朋友可以參考下2014-11-11
Python PyQt5中彈出子窗口解決子窗口一閃而過的問題
這篇文章主要介紹了Python PyQt5中彈出子窗口解決子窗口一閃而過的問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
Python函數(shù)isalnum用法示例小結(jié)
isalnum()函數(shù)是Python中的一個內(nèi)置函數(shù),用于判斷字符串是否只由數(shù)字和字母組成,其內(nèi)部實(shí)現(xiàn)原理比較簡單,只需遍歷字符串中的每一個字符即可,這篇文章主要介紹了Python函數(shù)isalnum用法介紹,需要的朋友可以參考下2024-01-01
pytorch之torchvision.transforms圖像變換實(shí)例
今天小編就為大家分享一篇pytorch之torchvision.transforms圖像變換實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12

