搜索
首页后端开发Python教程python3.4.3下逐行读入txt文本并去重的方法

这篇文章主要介绍了关于python3.4.3下逐行读入txt文本并去重的方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

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

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()

结果:

去重前:

去重后(无序):

去重后(有序):

总结

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

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

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

报错是因为程序没办法直接保存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"你好")

相关推荐:

python下解压缩zip文件并删除文件的实例_python


以上是python3.4.3下逐行读入txt文本并去重的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
在Python阵列上可以执行哪些常见操作?在Python阵列上可以执行哪些常见操作?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

在哪些类型的应用程序中,Numpy数组常用?在哪些类型的应用程序中,Numpy数组常用?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

您什么时候选择在Python中的列表上使用数组?您什么时候选择在Python中的列表上使用数组?Apr 26, 2025 am 12:12 AM

useanArray.ArarayoveralistinpythonwhendeAlingwithHomeSdata,performance-Caliticalcode,orinterFacingWithCcccode.1)同质性data:arrayssavememorywithtypedelements.2)绩效code-performance-clitionalcode-clitadialcode-critical-clitical-clitical-clitical-clitaine code:araysofferferbetterperperperformenterperformanceformanceformancefornalumericalicalialical.3)

所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?所有列表操作是否由数组支持,反之亦然?为什么或为什么不呢?Apr 26, 2025 am 12:05 AM

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactssperformance.2)listssdonotguaranteeconeeconeconstanttanttanttanttanttanttanttanttimecomplecomecomecomplecomecomecomecomecomecomplecomectaccesslikearrikearraysodo。

您如何在python列表中访问元素?您如何在python列表中访问元素?Apr 26, 2025 am 12:03 AM

toAccesselementsInapythonlist,useIndIndexing,负索引,切片,口头化。1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Python的科学计算中如何使用阵列?Python的科学计算中如何使用阵列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何处理同一系统上的不同Python版本?您如何处理同一系统上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

与标准Python阵列相比,使用Numpy数组的一些优点是什么?与标准Python阵列相比,使用Numpy数组的一些优点是什么?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具