您的位置:首页 > 编程语言 > Python开发

【PYTHON】对整个文件进行正则表达式匹配

2015-06-06 22:00 776 查看
#coding:utf-8
import re
def IDXtoSCS(path):#IDX转换为开思的函数
IDXfile=open(path,'r')
fileread=IDXfile.readlines()
IDXfile.close()
p='"(\w)*",\s+(\d+\\.\d+),\s+(\d+\\.\d+),\s+(\d+\\.\d+),\s+"(\w*)",'
data=re.findall(p,fileread)
print data
IDXtoSCS('C:/Users/Administrator/Desktop 2/0409.IDX')


上面这段代码是想实现对整个文件进行RE匹配,用findall找出所有与正则表达式匹配的字符串

但是运行后出现:

File "C:\Users\Administrator\Desktop 2\IDXtoSCS.py", line 8, in IDXtoSCS
data=re.findall(p,fileread)
File "C:\Python27\lib\re.py", line 181, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer

问题出在file.readlines()上

在IDLE里输入help(file.readline)

>>> help(file.readlines)
Help on method_descriptor:

readlines(...)
readlines([size]) -> list of strings, each a line from the file.

Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.


readlines是文件的每行字符串的链表,而re.findall()方法需要的argument是字符串
将fileread=IDXfile.readlines()换成fileread=IDXfile.read()就解决了
因为file.read()返回的是整个文件的字符串
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: