前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >基于Python实现对各种数据文件的操作

基于Python实现对各种数据文件的操作

作者头像
1480
发布2019-07-10 15:13:06
2.4K0
发布2019-07-10 15:13:06
举报
文章被收录于专栏:数据分析1480数据分析1480

本文总结使用Python对常见的数据文件进行读写操作。

常见的数据文件类型如下:

  • txt
  • csv
  • excel(xls\xlsx)
  • 在线网页数据
  • pdf\word
  • 其他数据软件格式

1 txt文件

更多参考:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

文件读取

代码语言:javascript
复制
# 文件input
file_txt = os.path.join(workdir,'Data/demo_text.txt')

# 打开文件
f = open(file_txt, encoding='utf-8')

# 将每行的文本读取,并存为列表
# 此处使用.rstrip()去除空格、换行符
lines_raw = [x.rstrip() for x in f]
# 或者
# lines_raw = [l.rstrip() for l in f.readlines()]

print(lines_raw)

# 关闭文件
f.close()

输出如下:

['010杜甫:佳人', '', '绝代有佳人,幽居在空谷。', '自云良家子,零落依草木。', '关中昔丧乱,兄弟遭杀戮。', '官高何足论,不得收骨肉。', '世情恶衰歇,万事随转烛。', '夫婿轻薄儿,新人美如玉。', '合昏尚知时,鸳鸯不独宿。', '但见新人笑,那闻旧人哭!', '在山泉水清,出山泉水浊。', '侍婢卖珠回,牵萝补茅屋。', '摘花不插发,采柏动盈掬。', '天寒翠袖薄,日暮倚修竹。']

也可以用pandas来读取

代码语言:javascript
复制
df_txt = pd.read_csv(file_txt, names=['txt'], encoding='utf-8')
df_txt.head()

输出如下:

文件输出

代码语言:javascript
复制
# 文件output
file_out = os.path.join(workdir,'Data/out_text.txt')

f_out = open(file_out, encoding='utf-8',mode = 'w')

f_out.writelines(lines_raw)
f_out.close()

2 csv文件

更多参考:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html#pandas.read_csv

csv文件的读入和写出相对简单,直接调用pandas的函数即可。

代码语言:javascript
复制
# 定义文件路径
file_csv = os.path.join(workdir,'Data/demo_csv.csv')

# pandas.read_csv()函数来读取文件
df_csv = pd.read_csv(file_csv,sep=',',encoding='utf-8')

# dataframe.to_csv()保存csv文件
df_csv.to_csv('out_csv.csv',index=False,encoding='utf-8')

# 查看dataframe前3行
df_csv.head(3)

输出如下:

也可以把csv当做文本文件来读取,不过处理过程稍微复杂点,尤其是字段内的取值中含有分隔符(比如逗号)时,例如上面的name字段。

3 excel(xls\xlsx)文件

pandas工具包中也提供了相应的函数来读写excel文件(pandas.read_excel()dataframe.to_excel())。

更多参考:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html#pandas.read_excel

不同于csv文件,xlsx文件中会有多个sheet,pandas.read_excel函数默认读取第一个sheet.

代码语言:javascript
复制
# 定义文件路径
file_excel = os.path.join(workdir,'Data/demo_xlsx.xlsx')

# pandas.read_excel()函数来读取文件
# sheet_name=0表示读取第一个sheet,也可以指定要读取的sheet的名称(字符串格式)
# header=0 表示使用第一行作为表头(列名)
# 如果数据中没有列名(表头),可以设置header=None,同时names参数来指定list格式的列名
df_excel = pd.read_excel(file_excel,sheet_name=0,header=0,encoding='utf-8')

# dataframe.to_csv()保存csv文件
df_excel.to_excel('out_excel.xlsx',index=False,encoding='utf-8')

# 查看dataframe前3行
df_excel.head(3)

如果我们是想在单元格颗粒度上进行操作,可以考虑两个工具包:

  • xlwings, https://www.xlwings.org/
  • openpyxl, https://openpyxl.readthedocs.io/en/stable/

这里用xlwings示范自动化“填表”,比如现在有3个项目对应的3个单元格需要填写。

代码语言:javascript
复制
import xlwings as xw

file_excel = os.path.join(workdir,'Data/demo_填表.xlsx')

# 打开excel文件的时候不要展示页面
app = xw.App(visible=False)

# 打开工作簿
wb = xw.Book(file_excel)

# 打开工作表
# 可以用index,可以指定sheet的名称
ws = wb.sheets[0]

# 读取对应单元格的值
print(ws.range('A1').value)

ws.range('B1').value = 'Ahong'
ws.range('B2').value  = '男'
ws.range('B3').value  = 'Pyhon'

# 保存工作簿
wb.save() 
# 也可以保存为新的文件名,e.g.wb.save('new.xlsx')

# 关闭工作簿
wb.close()

如果要批量从多个统一格式的excel文件中读取多个单元格或者写入数据,不妨考虑此方法。

4 在线网页数据

在线网页数据通常需要网络爬虫来抓取,同时网页是半结构化的数据,需要整理为结构化的数据。

注:关于网络爬虫可以参考O'REILLY的书Web Scraping with Python: Collecting More Data from the Modern Web).

网页数据的爬取和解析常会用到的工具包:

  • requests, https://2.python-requests.org//zh_CN/latest/user/quickstart.html
  • BeautifulSoup, https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.html
  • lxml, https://lxml.de/, 笔者最喜欢用的工具包之一
  • re, https://docs.python.org/3/library/re.html,正则化是数据清洗中必学的技能之一,更多参考https://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html
  • json, https://docs.python.org/3/library/json.html, 处理json格式数据
  • pandas, https://pandas.pydata.org/pandas-docs/stable/index.html,将数据保存为dataframe

通常网络爬虫的步骤如下:

  1. 分析网页请求规范,比如是get还是post,请求的url是啥,返回的数据是什么格式(json?静态html?),header参数,url或者post中的变量有什么等;
  2. 获取网页数据,使用requests包;
  3. 解析网页数据(将半结构化的网页数据转化为结构化数据),BeautifulSoup、lxml、re、json齐上阵;
  4. 整合数据并存档,使用pandas对数据进行整合并初步清洗。

5 PDF\Word

5.1 读取PDF文件

对于pdf文件而言,如果要对文档操作(比如合并、筛选、删除页面等),建议使用的工具包:

  • PyPDF2, http://mstamy2.github.io/PyPDF2/
  • pdfrw, https://github.com/pmaupin/pdfrw

更多参考:https://www.binpress.com/manipulate-pdf-python/

处理pdf文件时,要注意文件需要是“已解密”或者“无密码”状态,“加密”状态的文件处理时会报错。

pdf解密工具推荐:

  • http://freemypdf.com/
  • https://smallpdf.com/unlock-pdf

这里举例说明PyPDF2的用法,筛选奇数页面并保存为新文档。

代码语言:javascript
复制
import PyPDF2

# 读入文件路径
file_in = os.path.join(workdir,'Data/demo_pdf.pdf')
# 打开要读取的pdf文件
f_in = open(file_in,'rb') 

# 读取pdf文档信息
pdfReader = PyPDF2.PdfFileReader(f_in)

# pdf文件页面数
page_cnt = pdfReader.getNumPages()

pdfWriter = PyPDF2.PdfFileWriter()

# 筛选奇数页面
for page_idx in range(0,page_cnt,2):
    page = pdfReader.getPage(page_idx)
    pdfWriter.addPage(page)

# 输出文档
file_out = open('pdf_out.pdf', 'wb')
pdfWriter.write(file_out)

# 关闭输出的文件
file_out.close()

# 关闭读入的文件
pdf_file.close()

如果要解析pdf文件的页面数据(文件上都写了啥),推荐的工具包为:

  • textract, https://textract.readthedocs.io/en/stable/,该工具包支持多种格式文件的数据提取
  • pdfminer.six, https://github.com/pdfminer/pdfminer.six,使用方法同pdfminer是一样的。pdfminer的使用方法参考http://www.unixuser.org/~euske/python/pdfminer/

安装好pdfminer.six后,直接在命令行中调用如下命令即可:

pdf2txt.py demo_pdf.pdf -o demo_pdf.txt

或者参考https://stackoverflow.com/questions/26494211/extracting-text-from-a-pdf-file-using-pdfminer-in-python可以自定义一个函数批量对pdf进行转换(文末附有该函数)。

textract使用示例如下

代码语言:javascript
复制
import textract

# 文件路径
file_pdf = os.path.join(workdir,'Data/demo_pdf.pdf')

# 提取文本
text_raw = textract.process(file_pdf)
# 转码
text = text_raw.decode('utf-8')

5.2 读取Word文件

可以使用工具包python-docx,https://python-docx.readthedocs.io/en/latest/

操作word的场景相对少见,参考网站的示例即可。

6 其他数据软件文件

比如SAS, SPSS,Stata等分析软件导出的数据格式。

可以使用的工具包pyreadstat, https://github.com/Roche/pyreadstat

代码语言:javascript
复制
# 使用Python读取.sav文件
# https://github.com/Roche/pyreadstat
import pyreadstat

# 文件路径
file_data = os.path.join(workdir,'Data/demo_sav.sav')

# 读取文件
df,meta = pyreadstat.read_sav(file_data)
# df就是转化后的数据框

# 查看编码格式
print(meta.file_encoding)

df.head()

示例数据下载: https://pan.baidu.com/s/1iGU5vjDrwGzBswbxsC714Q 提取码: sjgz

更多参考

  • https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html
  • Automate the Boring Stuff with Python: Practical Programming for Total Beginners

附PDF文件转字符串的函数

代码语言:javascript
复制
# ref: https://stackoverflow.com/questions/26494211/extracting-text-from-a-pdf-file-using-pdfminer-in-python

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-07-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数据分析1480 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档