Python TypeError:强制转换为Unicode:需要字符串或缓冲区,找到int

时间:2015-04-09 05:30:36

标签: python string unicode

我在&news;'和“发送”中的句子数组。 我需要打印“发送”中的所有句子。至少有一个单词在' newsorted' 。 这是我的代码。

for s in sent:
    for w in newsorted :
        if w in s:
            print "------\n",s
            break

运行代码时出现以下错误

Traceback (most recent call last):
  File "withreferences.py", line 181, in <module>
    if w in s:
TypeError: coercing to Unicode: need string or buffer, int found

提前致谢。

2 个答案:

答案 0 :(得分:2)

这样做的好方法如下。

newsorted = ['the', 'me', 'you', 'picture']
sent = ["The man left the store.", "You are fun.", "That's me!"]

for s in sent:
    sentence = ''.join(filter(lambda x: x.isalpha() or x in [' ', "'"], list(s)))
    words = sentence.lower().split(' ')
    shared_words = set(words) & set(newsorted)
    if bool(shared_words):
        print("------\n" + s)

运行此命令将输出:

------
The man left the store.
------
You are fun.
------
That's me!

但是,您获得的错误很可能是由您的某个列表的内容引起的。在不知道您使用的列表中的内容的情况下,我们无法进一步帮助。

答案 1 :(得分:1)

您的数组中的某个对象可能没有错误地实现特殊方法__unicode __ ()。如果它返回int,则存在异常Python TypeError: coercing to Unicode: need string or buffer, int found。如果它们都是标准字符串,请检查数组中的对象类型。