python - 类型错误 : expected string or buffer

标签 python regex

我有这个简单的代码:

import re, sys

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

我不知道为什么会出现错误:

'expected string or buffer'

谁能帮忙?

最佳答案

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'>

来自 help(file.readlines)。 IE。 readlines() 用于循环/迭代:

readlines(...)
    readlines([size]) -> list of strings, each a line from the 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']

关于python - 类型错误 : expected string or buffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16193521/

相关文章:

Python Flask 提交按钮不起作用

python - 如何使用 pymox 对该代码进行单元测试?

python - 为类(class)定制双星运营商?

regex - 如何将字符串向量转换为标题大小写

javascript - 正则表达式和xml

python - 如何使用stackoverflow api获取 'user'数据?

python - 将又长又慢的 jupyter-notebook 分成不同的 block

regex - 如何找到分号分隔值的计数?

python - 在 Python 正则表达式 split() 中访问定界符

Javascript 正则表达式多重匹配