python文本处理
Ⅰ 用 python 可以来做什么
Web 和 Internet开发;科学计算和统计;人工智能;桌面界面开发;软件开发;后端开发;网络接口:能方便进行系统维护和管理,Linux下标志性语言之一,是很多系统管理员理想的编程工具。
Python的设计目标之一是让代码具备高度的可阅读性。它设计时尽量使用其它语言经常使用的标点符号和英文单字,让代码看起来整洁美观。它不像其他的静态语言如C、Pascal那样需要重复书写声明语句,也不像它们的语法那样经常有特殊情况和意外。
Python标准库的主要功能有:
1、文本处理,包含文本格式化、正则表达式匹配、文本差异计算与合并、Unicode支持,二进制数据处理等功能
2、文件处理,包含文件操作、创建临时文件、文件压缩与归档、操作配置文件等功能
3、操作系统功能,包含线程与进程支持、IO复用、日期与时间处理、调用系统函数、写日记(logging)等功能
4、网络通信,包含网络套接字,SSL加密通信、异步网络通信等功能
5、网络协议,支持HTTP,FTP,SMTP,POP,IMAP,NNTP,XMLRPC等多种网络协议,并提供了编写网络服务器的框架
6、W3C格式支持,包含HTML,SGML,XML的处理
7、其它功能,包括国际化支持、数学运算、HASH、Tkinter等
Ⅱ python 处理文本,格式化文本~
#coding=utf-8
records=[]
record={}
withopen("data.txt")asf:
whileTrue:
line=f.readline()
ifnotline:
iflen(record)!=0:records.append(record)
break
field=line[line.find(":")+1:].strip()
ifline.startswith("ScopeId"):
iflen(record)!=0:records.append(record)
record={}
record["ScopeId"]=field
elifline.startswith("Name"):
record["Name"]=field
elifline.startswith("Free"):
record["Free"]=field
elifline.startswith("InUse"):
record["InUse"]=field
elifline.startswith("PercentageInUse"):
record["PercentageInUse"]=field
#设置缺省项
forrinrecords:
r.setdefault("InUse",0)
r.setdefault("PercentageInUse",0)
r.setdefault("Name","")
r.setdefault("Free",0)
printrecords
Ⅲ python文本处理问题
请把文件放到网络网盘,便于大家测试。
Ⅳ python 文本文件数据处理
分隔日志文件存为小文件
#coding:utf-8
#file: FileSplit.py
import os,os.path,time
def FileSplit(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
number = 100000 #每个小文件中保存100000条数据
dataLine = sFile.readline()
tempData = [] #缓存列表
fileNum = 1
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
for row in range(number):
tempData.append(dataLine) #将一行数据添加到列表中
dataLine = sFile.readline()
if not dataLine :
break
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + str(fileNum) + ".txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tempData) #将列表保存到文件中
tFile.close()
tempData = [] #清空缓存列表
print(tFilename + " 创建于: " + str(time.ctime()))
fileNum += 1 #文件编号
sFile.close()
if __name__ == "__main__" :
FileSplit("access.log","access")
分类汇总小文件:
#coding:utf-8
#file: Map.py
import os,os.path,re
def Map(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
dataLine = sFile.readline()
tempData = {} #缓存列表
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
p_re = re.compile(r'(GET|POST)s(.*?)sHTTP/1.[01]',re.IGNORECASE) #用正则表达式解析数据
match = p_re.findall(dataLine)
if match:
visitUrl = match[0][1]
if visitUrl in tempData:
tempData[visitUrl] += 1
else:
tempData[visitUrl] = 1
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + ' ')
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + "_map.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Map("access\access.log1.txt","access")
Map("access\access.log2.txt","access")
Map("access\access.log3.txt","access")
3. 再次将多个文件分类汇总为一个文件。
#coding:utf-8
#file: Rece.py
import os,os.path,re
def Rece(sourceFolder, targetFile):
tempData = {} #缓存列表
p_re = re.compile(r'(.*?)(d{1,}$)',re.IGNORECASE) #用正则表达式解析数据
for root,dirs,files in os.walk(sourceFolder):
for fil in files:
if fil.endswith('_map.txt'): #是rece文件
sFile = open(os.path.abspath(os.path.join(root,fil)), 'r')
dataLine = sFile.readline()
while dataLine: #有数据
subdata = p_re.findall(dataLine) #用空格分割数据
#print(subdata[0][0]," ",subdata[0][1])
if subdata[0][0] in tempData:
tempData[subdata[0][0]] += int(subdata[0][1])
else:
tempData[subdata[0][0]] = int(subdata[0][1])
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + ' ')
tFilename = os.path.join(sourceFolder,targetFile + "_rece.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Rece("access","access")
Ⅳ python具体在文本处理上怎么用
在诸多软件压缩包中或是项目压缩包中都会存在一个readme.txt文件,其中的内容无非是对软件的简单介绍和注意事项。但是在该文本文件中,内容没有分段分行,是非常冗杂地混在一起。当然处理手段多种多样,而我正好尝试利用Python解决这个问题。另外,这些内容或许对将来爬虫爬下的内容进行处理也是有些帮助的,只不过面对的混乱和处理需求不同而已。
这里的思路很简单,打开一个文本文档,对其中具有两个及两个以上的空格进行处理,即产生换行,另外出现很多的‘=’和‘>>>’也进行处理。这里我尝试处理的是easyGUI文件夹中的read.txt,该文件我复制在了D盘的根目录下。具体的实现代码如下:
def save_file(lister):#将传入的列表保存在新建文件中 new_file = open('new_file','w')#创建并打开文件,文件可写 new_file.writelines(lister)#将列表lister中的内容逐行打印 new_file.close()#关闭文件,且缓存区中的内容保存至该文件中def split_file(filename):#分割原始文件 f = open(filename)#打开该原始文件,默认该文件不可修改 lister = []#初始化一个空列表 for each_line in f: if each_line[:6] != '======' and each_line[:3] != '>>>': #当连续出现六个‘=’或连续三个‘>’时,打印一个换行符,实际体现在else中 each_line.split(' ',1)#当出现两个空格时,分割一次,并在下一行代码中以一行的形式保存在列表中 lister.append(each_line) else:
lister.append('\n')
save_file(lister)
f.close()
split_file('D:\\README.txt')
代码给出了详细的注释。其中得到的新的名为“new_file”的文件保存在默认的Python项目的目录下。当然,可以通过chdir()更改工作目录,使得文件创建在自己指定的位置。
Ⅵ python对文本文件的读有哪些方法,写有哪些方法
1 文件读取全文本操作
在一定场景下我们需要把文本全部内容读取出来,进行处理。python提供三种函数读取文件,分别是read readline readlines,
read():读取文件的全部内容,加上参数可以指定读取的字符。
readline():读取文件的一行。
readlines():读取文件的所有行到内存中。
不同场景下我们可以选择不同函数对文件进行读取。
1.1 方法一
file_name = input("请输入你要打开的文件的完整路径及名称")
file= open(file_name, "r")
txt=file.read()
# 全文本的处理
file.close()
使用read函数将文件中的内容全部读取,放在字符串变量txt中。这样操作适合于文本较小,处理简单的情况,当文件较大时,这种方式处理时不合适的。一次性读取较大的文件到内存中,会耗费较多的时间和资源。这时候分批处理效果更好。
1.2 方法二
file_name = input("请输入你要打开的文件的完整路径及名称")
file= open(file_name, "r")
txt= file.read(4)
# 文本的处理while txt != ""txt= file.read(4)
# 批量文本处理
file.close()
这种方法适合于分批处理文本信息,每次批量读入,批量处理,不会对内存造成较大的压力。
1.3 方法三
file_name = input("请输入你要打开的文件的完整路径及名称")
file= open(file_name, "r")for line infile.readlines():
# 处理每一行数据
file.close()
这种处理方式适合处理以行为分割特点的文本,并且文本较小,因为这种处理方式需要一次性把文件所有内容读取到内存中。
1.4 方法四
file_name = input("请输入你要打开的文件的完整路径及名称")
file= open(file_name, "r") # 这里的file时文件句柄for line infile:
# 处理每一行数据
file.close()
这种方式和方法三中的区别是分行读入,逐行处理,不会一次性把文件所有内容都读入到内存中,对一些大文件的处理是很有效的。
2 文件写入文本操作
文件写入有两种写入函数和一种辅助支持。
write():向文件中写入一个字符或者字节流
writelines():将一个元素全为字符串的列表写入到文件中 需要注意的是,writelines写入列表元素的时候会把列表元素的内容拼接到一起写入,不会有换行和空格 。
seek(): 辅助写入函数offset偏移量参数代表含义如下
0 - 文件开头
1 - 当前位置
2 - 文件结尾
2.1 方法一
file_name = input("output.txt", "w+")
text= "hello world!"file_name.write(text)
file.close()
2.2 方法二
file_name = input("output.txt", "w+")
list= ["中午","早上","晚上"]
file_name.writelines(list)for line infile:
# 读取写入的数据,这时候发现是没有任何内容的
file.close()
我们增加一行代码就可以读取到写入的文件内容,利用seek()函数调整写操作指针的位置,可以实现写操作之后的正常读取。
file_name = input("output.txt", "w+")
list= ["中午","早上","晚上"]
file_name.readlines(list)
file_name.seek(0) # 调整写的指针到文件的开始位置for line infile:
# 读取写入的数据,这时候会读出一行写入的数据。
file.close()
Ⅶ python 文本文件处理
简单的方法是直接做个正则表达式把文件提出来
s=open("file1.txt","rb").read()
import re
files=re.findall("(?isu)file.*?txt",s)
for f in files:
print "/root/usr/%s"%f
这样不知道能不能满足你的需求。
Ⅷ 如何用python进行文本预处理
#!/usr/bin/python
#print"HelloWorld"
str_seperator="=================================================================================="
timePointName=["enterOpenNextImageat",#0
"enterOpenImageat",#1
"InOpenImagesendOn_ImageRefreshat",#2
"leaveOpenImageat",#3
"leaveOpenNextImageat",#4
"enterLoadImageat",#5
"decodebeganat",#6
"enterDrawClientat",#7
"leaveDrawClientat",#8
"decodeendat",#9
"inLoadImagesendOn_ImageRefreshat",#10
"leaveloadImageat",#11
"secondenterDrawClientat",#12
"secondleaveDrawClientat"#13
]
itemNumber=0;
avgTotal=0;#13-0
avgFirstDraw=0;#8-2
avgLoadImage=0;#11-5
avgSecondDraw=0;#13-10
fobj=open("F:log.txt","r")
imageTimeSta={}
dic={}
path=""
idx=0
forlineinfobj:
idx=idx+1
ifidx==1:
line=line[3:]
else:
pass
line=line.strip()
line=line.decode("utf-8").encode("gbk")
ifline==str_seperator:
ifpath=="":
pass
else:
imageTimeSta[path]=dic
dic={}
path=""
continue
tabIndex=line.find(' ')
iftabIndex==-1:
path=line
printpath
continue
tabLastIndex=line.rfind(' ')
name=line[0:tabIndex]
time=int(line[tabLastIndex+1:])
ifnameindic:
dic["second"+name]=time
else:
dic[name]=time
fobj.close()
itemNumber=len(imageTimeSta)
keys=imageTimeSta.keys();
for(k,dic)inimageTimeSta.iteritems():
avgTotal+=dic[timePointName[13]]-dic[timePointName[0]];
avgFirstDraw+=dic[timePointName[8]]-dic[timePointName[2]];
avgLoadImage+=dic[timePointName[11]]-dic[timePointName[5]];
avgSecondDraw+=dic[timePointName[13]]-dic[timePointName[10]];
print'avgTotal',avgTotal/float(itemNumber)
print'avgFirstDraw',avgFirstDraw/float(itemNumber)
print'avgLoadImage',avgLoadImage/float(itemNumber)
print'avgSecondDraw',avgSecondDraw/float(itemNumber)
#printimageTimeSta