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

 1 #coding:utf-8
 2 import re
 3 def IDXtoSCS(path):#IDX转换为开思的函数
 4     IDXfile=open(path,'r')
 5     fileread=IDXfile.readlines()
 6     IDXfile.close()
 7     p='"(\w)*",\s+(\d+\\.\d+),\s+(\d+\\.\d+),\s+(\d+\\.\d+),\s+"(\w*)",'
 8     data=re.findall(p,fileread)
 9     print data
10 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()返回的是整个文件的字符串

转载于:https://www.cnblogs.com/alvysinger/p/4557383.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值