【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()返回的是整個文件的字符串


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM