我有这个简单的代码:
import re, sys
f = open('findallEX.txt', 'r')
lines = f.readlines()
match = re.findall('[A-Z]+', lines)
print match
Run Code Online (Sandbox Code Playgroud)
我不知道为什么我收到错误:
'期望字符串或缓冲区'
有人可以帮忙吗?
tim*_*mss 32
lines
是一个清单.re.findall()
没有列表.
>>> 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'>
Run Code Online (Sandbox Code Playgroud)
来自help(file.readlines)
.即readlines()
用于循环/迭代:
readlines(...)
readlines([size]) -> list of strings, each a line from the file.
Run Code Online (Sandbox Code Playgroud)
要查找文件中的所有大写字符:
>>> 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']
Run Code Online (Sandbox Code Playgroud)
lines
是一个字符串列表,re.findall
不适用于此.尝试:
import re, sys
f = open('findallEX.txt', 'r')
lines = f.read()
match = re.findall('[A-Z]+', lines)
print match
Run Code Online (Sandbox Code Playgroud)