脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python利用pandas将excel文件转换为txt文件的方法

python利用pandas将excel文件转换为txt文件的方法

2021-04-12 00:09NStock20133 Python

今天小编就为大家分享一篇python利用pandas将excel文件转换为txt文件的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

python将数据换为txt的方法有很多,可以用xlrd库实现。本人比较懒,不想按太多用的少的插件,利用已有库pandasexcel文件转换为txt文件。

直接上代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
'''
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='保存路径/'+'文件名'

以上这篇python利用pandas将excel文件转换为txt文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/teacher20133/article/details/79410464

延伸 · 阅读

精彩推荐