类型错误:预期的字符串或缓冲区 [英] TypeError: expected string or buffer

查看:67
本文介绍了类型错误:预期的字符串或缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的代码:

import re, sysf = open('findallEX.txt', 'r')行 = f.readlines()match = re.findall('[A-Z]+', 行)打印匹配

我不知道为什么我收到错误:

<块引用>

'期望的字符串或缓冲区'

有人可以帮忙吗?

解决方案

lines 是一个列表.re.findall() 不接受列表.

<预><代码>>>>进口重新>>>f = open('README.md', 'r')>>>行 = f.readlines()>>>match = re.findall('[A-Z]+', 行)回溯(最近一次调用最后一次):文件<input>",第 1 行,在 <module> 中findall 中的文件/usr/lib/python2.7/re.py",第 177 行返回 _compile(pattern, flags).findall(string)类型错误:预期的字符串或缓冲区>>>类型(行)<输入列表">

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

readlines(...)readlines([size]) ->字符串列表,每一行都来自文件.

要查找文件中的所有大写字符:

<预><代码>>>>进口重新>>>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']

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

这篇关于类型错误:预期的字符串或缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆