Python使用集合将txt文件重复行去除
2023-09-11 14:16:29 时间
最近爬取了百度百科一些关键词的infobox,由于关键词也是从百度百科页面大量爬取的,其中有诸多重复,于是使用集合将重复的关键词去掉,此方法也适用于其他类型重复行的去除。
def remove_duplicates(path):
with open(path, 'r', encoding = 'utf-8') as f:
lines = f.readlines()
unique_lines = set(lines)
with open(path, 'w', encoding = 'utf-8') as f:
f.writelines(list(unique_lines))
remove_duplicates("想要去重的文件名.txt")
运行代码,将重复行去除后重新写回此文本,文本内每行顺序也会被打乱,可以定义排序规则最后进行排序。 如果报错基本是编码格式的问题,可以将"utf-8"换成需要的编码“gbk”、“gb2312”等,有时候直接将encoding删掉也可能会解决报错。
相关文章
- python读写文件write和flush
- python code practice(四):树、图
- python 字典
- MVC模式:python案例
- 【29】Windows找不到文件:‘depthaidepthai_demo_pythonpython.exe‘。请检查文件名是否正确后,再试一次。
- Python asyncio编程之异步与非异步模块混合异步实现
- Atitit.提升软件Web应用程序 app性能的方法原理 h5 js java c# php python android .net
- Python语言编程学习:文件路径变量修改,利用os模块固定文件父路径,变换文件子路径实现代码
- Python语言学习:解决python版本升级问题集合(python2系列→Python3系列)导致错误的总结集合
- TF:基于tensorflow框架利用python脚本下将YoloV3训练好的.ckpt模型文件转换为推理时采用的.pb文件
- 〖Python自动化办公篇⑨〗- word文件自动化 - 设置Word全局样式和文本样式
- 〖Python 数据库开发实战 - Python与MySQL交互篇⑩〗- 创建新闻管理系统的具体python文件
- 〖Python 数据库开发实战 - MongoDB篇⑧〗- MongoDB的数据结构
- python判断文件类型是否是gz、tar、zip类型的文件(亲测可用)
- python快速读取非常大的文件
- [ Python入门教程 ] Python文件基本操作_shutil模块
- Python 解析含有命名空间(xmlns)的xml文件(基于ElementTree)
- [python]CompressionError: bz2 module is not available
- Python输出小数格式控制
- python kafka权限校验client.id
- Python 头部 #!/usr/bin/python 和 #!/usr/bin/env 的区别
- 【异常】前端ERR! stack Error: Can‘t find Python executable “python“, you can set the PYTHON env variable.
- python文件读取操作练习题(统计单词)
- Python学习思维导图
- 【Python问题解决】---- ERROR: Could not install packages due to an OSError: [WinError 2] 系统找不到指定的文件。
- 【Python】MongoDB数据库安装和Pymongo操作学习
- Python .py 文件打包成 .exe 文件(Windows平台,python 3.x)