国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python做文本按行去重的實現方法

2019-11-25 16:31:12
字體:
來源:轉載
供稿:網友

文本:

每行在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] = lineelse:continueprint 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] = lineelse:continueprint line_dict_uniqprint len(line_dict_uniq)

繼續補充一個函數

# -*- coding: utf-8 -*-'''只使用與較小的文件,比較大的文件運行時間長'''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("源文件路徑","目標文件路徑")

以上所述是小編給大家介紹的Python做文本按行去重,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 长汀县| 新乡市| 自贡市| 赞皇县| 新和县| 开化县| 淮北市| 祁门县| 临沧市| 赣州市| 彰化市| 会昌县| 麻城市| 澄江县| 酒泉市| 安西县| 青岛市| 大城县| 和硕县| 梧州市| 五常市| 梨树县| 郸城县| 沁阳市| 秦皇岛市| 前郭尔| 武邑县| 南昌市| 石柱| 盐津县| 镇安县| 上犹县| 昌图县| 大连市| 图片| 浠水县| 乃东县| 奉新县| 南召县| 宜兴市| 永济市|