python利用pandas将excel文件转换为txt文件的方法
作者:NStock20133 时间:2022-04-05 18:49:01
python将数据换为txt的方法有很多,可以用xlrd库实现。本人比较懒,不想按太多用的少的插件,利用已有库pandas将excel文件转换为txt文件。
直接上代码:
'''
function:将excel文件转换为text
author:Nstock
date:2018/3/1
'''
import pandas as pd
import re
import codecs
#将excel转化为txt文件
def exceltotxt(excel_dir, txt_dir):
with codecs.open(txt_dir, 'w', 'utf-8') as f:
neg=pd.read_excel(excel_dir, header=None, index=None)
f.write(neg.to_string())
#去除记录行首的数字和空格
def del_linehead_number_speace(orig_txt_dir,saveas_txt_dir):
with open(orig_txt_dir,'r+') as f, open(saveas_txt_dir,'r+') as fw:
lines = f.readlines()
print(len(lines)) #行数
texts = [re.sub(r'(\d)+(\s)+','',lines[num]) for num in range(len(lines)) ]
texts = list(set(texts)) #去重如果要保留重复记录注释该行
line_num = len(texts)
# for num in range(line_num): #查看转化后的文本
# print(texts[num])
fw.writelines(texts)
exceltotxt('./data/neg.xls', './data/neg_temp.txt')
del_linehead_number_speace('./data/neg_temp.txt','./data/neg.txt')
说明:xxx_dir带目标文件名为:xxx_dir='保存路径/'+'文件名'
来源:https://blog.csdn.net/teacher20133/article/details/79410464
标签:python,pandas,excel,txt
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
2008年Logo设计10大趋势
2008-02-28 13:06:00
![](https://img.aspxhome.com/file/UploadPic/20082/28/200822813204572s.gif)
Dreamweaver MX弹出窗口全攻略
2010-09-05 21:14:00
![](https://img.aspxhome.com/file/UploadPic/20072/20072311313962s.jpg)
在PHP3中实现SESSION的功能(二)
2023-11-17 11:26:52
[译]2009年海外Web设计风潮(下)
2009-01-23 09:34:00
![](https://img.aspxhome.com/file/UploadPic/20091/23/trend-38-39s.gif)
python3实现读取chrome浏览器cookie
2023-10-18 13:18:44
巧妙的Sql函数日期处理方法
2009-05-25 17:59:00
python interpolate插值实例
2022-05-06 08:20:37
![](https://img.aspxhome.com/file/2023/4/84874_0s.jpg)
对“关于购物车的想法”的一些回复
2009-03-10 18:15:00
python数据分析之公交IC卡刷卡分析
2022-02-10 02:23:56
![](https://img.aspxhome.com/file/2023/5/75145_0s.png)
Python PyQt5实战项目之查询器的实现流程详解
2023-07-15 04:19:21
![](https://img.aspxhome.com/file/2023/8/78758_0s.png)
oracle 下WITH CHECK OPTION用法
2009-02-28 10:59:00
SQL Server 2005数据转换服务设计问题集锦
2008-12-26 17:29:00
Python实现Restful API的例子
2023-03-23 18:28:10
IE6终极备忘单——对IE6单独兼容[译]
2010-01-21 18:34:00
优化次数过多的循环
2009-11-12 12:35:00
再谈 Web 字体的现状与未来[译]
2009-11-24 13:55:00
![](https://img.aspxhome.com/file/UploadPic/200911/24/webfonts_example-thumb-640xauto-7429-10s.png)
ASP程序代码执行时间统计类
2007-10-15 12:45:00
该死的IE,走好
2009-01-15 12:26:00
![](https://img.aspxhome.com/file/UploadPic/20091/15/byebye_ie6-71s.png)
flash(swf)遮住网页内容div的解决
2007-10-31 07:29:00
JavaScript实现淘宝网图片的局部放大功能
2023-08-25 05:44:56
![](https://img.aspxhome.com/file/2023/0/56070_0s.jpg)