python3.4.3下逐行读入txt文本并去重的方法


Posted in Python onApril 29, 2018

读写文件时应注意的问题包括:

1.字符编码

2.操作完成即时关闭文件描述符

3.代码兼容性

几种方法:

#!/bin/python3
original_list1=[" "]
original_list2=[" "]
original_list3=[" "]
original_list4=[" "]
newlist1=[" "]
newlist2=[" "]
newlist3=[" "]
newlist4=[" "]
newtxt1=""
newtxt2=""
newtxt3=""
newtxt4=""
#first way to readline
f = open("duplicate_txt.txt","r+")    # 返回一个文件对象  
line = f.readline()           # 调用文件的 readline()方法 
while line:  
  original_list1.append(line)          
  line = f.readline()  
f.close() 
#use "set()" remove duplicate str in the list
# in this way,list will sort randomly
newlist1 = list(set(original_list1))
#newlist1 = {}.fromkeys(original_list1).keys() #faster 
#rebuild a new txt 
newtxt1="".join(newlist1)
f1 = open("noduplicate1.txt","w")
f1.write(newtxt1)
f1.close()
###################################################################
#second way to readline
for line in open("duplicate_txt.txt","r+"):  
  original_list2.append(line)
newlist2 = list(set(original_list2))
newlist2.sort(key=original_list2.index)         #sort
#newlist2 = sorted(set(original_list2),key=l1.index)  #other way
newtxt2="".join(newlist2)
f2 = open("noduplicate2.txt","w")
f2.write(newtxt2)
f2.close()
###################################################################
#third way to readline
f3 = open("duplicate_txt.txt","r")  
original_list3 = f3.readlines()       #读取全部内容 ,并以列表方式返回 
for i in original_list3:          #遍历去重
  if not i in newlist3:
      newlist3.append(i)
newtxt3="".join(newlist3)
f4 = open("noduplicate3.txt","w")
f4.write(newtxt3)
f4.close()
###################################################################
#fourth way
f5 = open('duplicate_txt.txt',"r+") 
try: 
  original_list4 = f5.readlines() 
  [newlist4.append(i) for i in original_list4 if not i in newlist4]
  newtxt4="".join(newlist4)
  f6 = open("noduplicate4.txt","w")
  f6.write(newtxt4)
  f6.close()
finally: 
  f5.close()

结果:

去重前:

python3.4.3下逐行读入txt文本并去重的方法

去重后(无序):

python3.4.3下逐行读入txt文本并去重的方法

去重后(有序):

python3.4.3下逐行读入txt文本并去重的方法

总结

这段下程序涉及文件读写操作以及链表List的操作,文章开头提到的几个问题,由于并没有使用中文,所以不关心编码,但这里还是要提一提:

f = open("test.txt","w")
f.write(u"你好")

上面这段代码如果在python2中运行会报错

python3.4.3下逐行读入txt文本并去重的方法

报错是因为程序没办法直接保存unicode字符串,要经过编码转换成str类型的二进制字节序列才可以保存。

write()方法会自动编码转换,默认使用ascii编码格式,而ascii不能处理中文,所以出现UnicodeEncodeError。

正确方式是在调用write()方法前,手动格式转换,用utf-8或者gbk转换成str。

f = open("test.txt","w")
text=u"你好"
text=text.encode(encoding='utf-8')
f.write(text)

关于close()问题:

不关闭会有什么影响呢?操作完成后,不关闭文件,会对系统资源造成浪费,因为系统可打开的文件描述符数量是有限的。Linux是65535。

一般来说close之后就OK了,但是也会存在特殊情况,比如说,在调用open()函数时就已经发生错误,权限不足,调用close()肯定报错。还有一种是在write()时,如果磁盘空间不足,报错,close()就没有机会执行了。正确的做法就是使用 try except 对异常进行捕获:

f = open("test.txt","w")
try:
  text=u"你好"
  text=text.encode(encoding='utf-8')
  f.write(text)
except: IOError as e:
  print("oops,%s"%e.args[0])
finally:
  f.close()

更优雅的写法是用 with…as。

with open("test.txt","w") as f:
  text=u"你好"
  f.write(text.encode(encoding='utf-8'))

文件对象实现上下午管理器协议,程序进入with语句时,会把文件对象赋值给变量f,在程序退出with时会自动的调用close()方法。

关于兼容性问题:

python2和python3的open()函数是不一样的,后者可以在函数中指定字符编码格式。

如何解决python2和python3的兼容open()问题呢?

使用io模块下的open()函数,python2中的io.open等价与python3的open函数

from io import open
with open("test.txt","w",encoding='utf-8') as f:
  f.write(u"你好")

以上这篇python3.4.3下逐行读入txt文本并去重的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中List.count()方法的使用教程
May 20 Python
使用Python对Excel进行读写操作
Mar 30 Python
在centos7中分布式部署pyspider
May 03 Python
使用Eclipse如何开发python脚本
Apr 11 Python
pycharm: 恢复(reset) 误删文件的方法
Oct 22 Python
python 统计一个列表当中的每一个元素出现了多少次的方法
Nov 14 Python
python实现文本界面网络聊天室
Dec 12 Python
Mac安装python3的方法步骤
Aug 09 Python
浅析python中while循环和for循环
Nov 19 Python
django中url映射规则和服务端响应顺序的实现
Apr 02 Python
opencv 实现特定颜色线条提取与定位操作
Jun 02 Python
pytorch使用horovod多gpu训练的实现
Sep 09 Python
Python使用re模块实现信息筛选的方法
Apr 29 #Python
Python排序算法之选择排序定义与用法示例
Apr 29 #Python
Python实现的直接插入排序算法示例
Apr 29 #Python
Python实现的堆排序算法示例
Apr 29 #Python
Python中实现变量赋值传递时的引用和拷贝方法
Apr 29 #Python
分享一下Python数据分析常用的8款工具
Apr 29 #Python
Python随机函数random()使用方法小结
Apr 29 #Python
You might like
PHP SEO优化之URL优化方法
2011/04/21 PHP
PHP mcrypt可逆加密算法分析
2011/07/19 PHP
php使用curl检测网页是否被百度收录的示例分享
2014/01/31 PHP
php微信公众号开发之微信企业付款给个人
2018/10/04 PHP
PHP扩展mcrypt实现的AES加密功能示例
2019/01/29 PHP
jQuery-onload让第一次页面加载时图片是淡入方式显示
2012/05/23 Javascript
javascript模块化是什么及其优缺点介绍
2013/09/02 Javascript
js如何判断访问是来自搜索引擎(蜘蛛人)还是直接访问
2015/09/14 Javascript
AngularJS下$http服务Post方法传递json参数的实例
2018/03/29 Javascript
vue 做移动端微信公众号采坑经验记录
2018/04/26 Javascript
详解Vue的钩子函数(路由导航守卫、keep-alive、生命周期钩子)
2018/07/24 Javascript
使用layui的layer组件做弹出层的例子
2019/09/27 Javascript
Postman动态获取返回值过程详解
2020/06/30 Javascript
原生JS实现记忆翻牌游戏
2020/07/31 Javascript
[08:07]DOTA2每周TOP10 精彩击杀集锦vol.8
2014/06/25 DOTA
为Python的web框架编写前端模版的教程
2015/04/30 Python
Django文件上传与下载(FileFlid)
2019/10/06 Python
使用Rasterio读取栅格数据的实例讲解
2019/11/26 Python
python 实现矩阵按对角线打印
2019/11/29 Python
pycharm 2020.2.4 pip install Flask 报错 Error:Non-zero exit code的问题
2020/12/04 Python
CSS3中的Media Queries学习笔记
2016/05/23 HTML / CSS
HTML5实现一个能够移动的小坦克示例代码
2013/09/02 HTML / CSS
10个最常见的HTML5面试题 附答案
2016/06/06 HTML / CSS
戴尔美国官网:Dell
2016/08/31 全球购物
新闻编辑自荐信
2013/11/03 职场文书
幼儿园新学期寄语
2014/01/18 职场文书
党性观念心得体会
2014/09/03 职场文书
机电专业毕业生自我鉴定2014
2014/10/04 职场文书
篮球友谊赛通讯稿
2014/10/10 职场文书
2014年个人工作总结范文
2014/11/07 职场文书
中学总务处工作总结
2015/08/12 职场文书
浅谈Python项目的服务器部署
2021/04/25 Python
CSS 还能这样玩?奇思妙想渐变的艺术
2021/04/27 HTML / CSS
PHP设计模式(观察者模式)
2021/07/07 PHP
postgresql使用filter进行多维度聚合的解决方法
2021/07/16 PostgreSQL
python神经网络Xception模型
2022/05/06 Python