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?
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']
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With