Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: expected string or buffer

Tags:

python

regex

I have this simple code:

import re, sys  f = open('findallEX.txt', 'r') lines = f.readlines() match = re.findall('[A-Z]+', lines) print match 

I don't know why I am getting the error:

'expected string or buffer'

Can anyone help?

like image 890
user2290969 Avatar asked Apr 24 '13 13:04

user2290969


2 Answers

lines is a list. re.findall() doesn't take lists.

>>> import re >>> f = open('README.md', 'r') >>> lines = f.readlines() >>> match = re.findall('[A-Z]+', lines) Traceback (most recent call last):   File "<input>", line 1, in <module>   File "/usr/lib/python2.7/re.py", line 177, in findall     return _compile(pattern, flags).findall(string) TypeError: expected string or buffer >>> type(lines) <type 'list'> 

From help(file.readlines). I.e. readlines() is for loops/iterating:

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

To find all uppercase characters in your file:

>>> import re >>> re.findall('[A-Z]+', open('README.md', 'r').read()) ['S', 'E', 'A', 'P', 'S', 'I', 'R', 'C', 'I', 'A', 'P', 'O', 'G', 'P', 'P', 'T', 'V', 'W', 'V', 'D', 'A', 'L', 'U', 'O', 'I', 'L', 'P', 'A', 'D', 'V', 'S', 'M', 'S', 'L', 'I', 'D', 'V', 'S', 'M', 'A', 'P', 'T', 'P', 'Y', 'C', 'M', 'V', 'Y', 'C', 'M', 'R', 'R', 'B', 'P', 'M', 'L', 'F', 'D', 'W', 'V', 'C', 'X', 'S'] 
like image 163
timss Avatar answered Sep 18 '22 02:09

timss


lines is a list of strings, re.findall doesn't work with that. try:

import re, sys  f = open('findallEX.txt', 'r') lines = f.read() match = re.findall('[A-Z]+', lines) print match 
like image 21
mata Avatar answered Sep 18 '22 02:09

mata