类型错误:需要字符串或bu

2024-05-19 14:32:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的代码:

import re, sys

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

我不知道为什么会出错:

'expected string or buffer'

有人能帮忙吗?


Tags: or代码importretxtstringmatchsys
3条回答

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)。一、 e.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']

lines是字符串列表,re.findall不适用于此。尝试:

import re, sys

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

readlines()将返回文件中所有行的列表,因此lines是一个列表。你可能想要这样的东西:

for line in f.readlines(): # Iterates through every line and looks for a match
#or
#for line in f:
    match = re.findall('[A-Z]+', line)
    print match

或者,如果文件不太大,可以将其作为单个字符串获取:

lines = f.read() # Warning: reads the FULL FILE into memory. This can be bad.
match = re.findall('[A-Z]+', lines)
print match

相关问题 更多 >