首页 / PYTHON / python遍历文件进行数据处理
python遍历文件进行数据处理
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python遍历文件进行数据处理,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1811字,纯文字阅读大概需要3分钟。
内容图文
![python遍历文件进行数据处理](/upload/InfoBanner/zyjiaocheng/843/4e037c99853543beb208553deee9b4b5.jpg)
背景
之前写过一个遍历文件夹进行处理的Python程序,但因为时间太久找不着了。。 导致只能自己再写一遍,于是决定将代码放置于博客之中,以便以后使用。
#!usr/bin/env python
#-*- coding:utf-8 -*-
import math
import os
import glob
import numpy as np
import jieba
import string
import jieba.analyse
def read_from_file(directions):
decode_set=['utf-8','gb18030','ISO-8859-2','gb2312','gbk','Error']#编码集
#编码集循环
for k in decode_set:
try:
file = open(directions,"r",encoding=k)
readfile = file.read()#这步如果解码失败就会引起错误,跳到except。
#print("open file %s with encoding %s" %(directions,k))#打印读取成功
#readfile = readfile.encode(encoding="utf-8",errors="replace")#若是混合编码则将不可编码的字符替换为"?"。
file.close()
break#打开路径成功跳出编码匹配
except:
if k=="Error":#如果碰到这个程序终止运行
raise Exception("%s had no way to decode"%directions)
continue
return readfile
filenames = []
filenames=glob.glob(r"C:/Users/Administrator/Documents/Tencent Files/937610520/FileRecv/TXT/*.txt")
filenameslen=len(filenames)
count=0
for filename in filenames:
print("%d : %d" %(count,filenameslen))
names=filename.find('TXT')+4
namee=filename.find('.txt')
f=open(filename,"rb")
content=f.readlines()
content=" ".join('%s' %id for id in content)
start=content.find('description')+16
overflow=content.find('comments')
end=content[start:].find('#')+start
if end>=overflow:
end=overflow
file = open(r"C:/Users/Administrator/Documents/Tencent Files/937610520/FileRecv/TXT/" +filename[names:namee]+'keyword' + '.txt','w')
file_data = content[start:end]
#基于TF-IDF算法进行关键词抽取
tfidf=jieba.analyse.extract_tags
keywords=tfidf(file_data)
for i in range(len(keywords)):
if len(keywords)<=0:
print("error,please check your input")
break
file.write(keywords[i]+'\n')
file.close()
count=count+1
print("%d : %d" %(count,filenameslen))
print("finished")
内容总结
以上是互联网集市为您收集整理的python遍历文件进行数据处理全部内容,希望文章能够帮你解决python遍历文件进行数据处理所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。