python文件数据提取怎么实现

发布时间:2022-08-24 16:30:14 作者:iii
来源:亿速云 阅读:142

这篇文章主要介绍了python文件数据提取怎么实现的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇python文件数据提取怎么实现文章都会有所收获,下面我们一起来看看吧。

前提提要

python2.0有无法直接读取中文路径的问题,需要另外写函数。python3.0在2018年的时候也无法直接读取。

现在使用的时候,发现python3.0是可以直接读取中文路径的。

需要自带或者创建几个txt文件,里面最好写几个数据(姓名,手机号,住址)

要求

写代码的时候最好,自己设几个要求,明确下目的:

思路

代码

import glob
import re
import xlwt
filearray=[]
data=[]
phone=[]
filelocation=glob.glob(r'课堂实训/*.txt')
print(filelocation)
for i in range(len(filelocation)):
file =open(filelocation[i])
file_data=file.readlines()
data.append(file_data)
print(data)
combine_data=sum(data,[])

print(combine_data)
for a in combine_data:
data1=re.search(r'[0-9]{11}',a)
phone.append(data1[0])
phone=list(set(phone))
print(phone)
print(len(phone))

#存到excel中
f=xlwt.Workbook('encoding=utf-8')
sheet1=f.add_sheet('sheet1',cell_overwrite_ok=True)
for i in range(len(phone)):
sheet1.write(i,0,phone[i])
f.save('phonenumber.xls')

运行结果

python文件数据提取怎么实现

会生成一个excel文件

python文件数据提取怎么实现

python文件数据提取怎么实现

分析

import glob
import re
import xlwt

globe用来定位文件,re正则表达式,xlwt用于excel

1)读取文件

filelocation=glob.glob(r'课堂实训/*.txt')

指定目录下的所有txt文件

2)读取数据

for i in range(len(filelocation)):
file =open(filelocation[i])
file_data=file.readlines()
data.append(file_data)
print(data)

将路径下的txt文件循环读取,按序号依次读取文件
打开每一次循环对应的文件
将每一次循环的txt文件的数据按行读取出来
使用append()方法将每一行的数据添加到data列表中
输出一下,可以看到将几个txt的文件数据以字列形式存在同一个列表

3)数据整理

combine_data=sum(data,[])

列表合并成一个列表

4)正则表达式匹配外加数据去重

print(combine_data)
for a in combine_data:
data1=re.search(r'[0-9]{11}',a)
phone.append(data1[0])
phone=list(set(phone))
print(phone)
print(len(phone))

set()函数:无序去重,创建一个无序不重复元素集

6)数据导出保存

#存到excel中
f=xlwt.Workbook('encoding=utf-8')
sheet1=f.add_sheet('sheet1',cell_overwrite_ok=True)
for i in range(len(phone)):
sheet1.write(i,0,phone[i])
f.save('phonenumber.xls')

关于“python文件数据提取怎么实现”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“python文件数据提取怎么实现”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. Python如何提取Excel的数据?
  2. Python提取json数据

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:Python中如何使用Frozenset对象

下一篇:MySQL之Innodb_buffer_pool_size怎么设置

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》