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

yipeiwu_com6年前Python基础

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='保存路径/'+'文件名'

以上这篇python利用pandas将excel文件转换为txt文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现从log日志中提取ip的方法【正则提取】

本文实例讲述了Python实现从log日志中提取ip的方法。分享给大家供大家参考,具体如下: log日志内容如下(myjob.log): 124.90.53.68 - - [05/F...

使用python和pygame制作挡板弹球游戏

使用python和pygame制作挡板弹球游戏

python是个很有趣的语言,可以在cmd命令窗口运行,还有很多的功能强大的模块。 学了一天pygame,用python和pygame写一个简单的挡板弹球游戏。 2018年6月21日 0...

Python3并发写文件与Python对比

这篇文章主要介绍了Python3并发写文件原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用python2在进行并发写的时候...

Python中函数参数设置及使用的学习笔记

Python中函数参数设置及使用的学习笔记

一、参数和共享引用: In [56]: def changer(a,b): ....: a=2 ....: b[0]='spam' ....: In [57...

pyinstaller打包程序exe踩过的坑

pyinstaller打包程序exe踩过的坑

基础环境 python 2.7.17 pyinstaller 3.5 安装pyinstaller pip install pyinstaller 坑,大坑,深坑 背景:...