【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()返回的是整个文件的字符串
相关文章推荐
- python绘图中使用公式时,解决\frac{}{}出来的字体太小的问题
- Python虚拟环境virtualenv
- Python打包为exe使用py2exe时中文乱码问题
- 安装python爬虫scrapy踩过的那些坑和编程外的思考
- 利用Python的pip.exe文件将.whl文件解压为py2exe
- python 对入参文本进行预处理成以一个空格为间隔的一维数组
- python 检索文件资源的方法 =>长期更新
- python with语句与上下文管理器
- php调用python
- python 使用scapy进行帧注入
- 设计模式 Template模式
- python 将命令行执行的屏幕输出赋值到out变量
- python字典排序
- python中的浅拷贝和深拷贝
- pythonanywhere下django无法匹配url问题解决
- Python自学笔记系列一——基础语法
- Python中步长索引解析
- Leetcode: Length of Last Word in python
- Python学习日记---函数
- python类型转换