属性错误:'_io.TextIOWrapper'对象没有'lower'属性。

8

我正在尝试运行 stack overflow 提供的一个示例,链接在这里

我再次将代码复制在此处:

from sklearn.feature_extraction.text import TfidfVectorizer
text_files = ['file1.txt', 'file2.txt']
documents = [open(f) for f in text_files]
tfidf = TfidfVectorizer().fit_transform(documents)
# no need to normalize, since Vectorizer will return normalized tf-idf
pairwise_similarity = tfidf * tfidf.T

我所添加的唯一内容是这行代码:
text_files = ['file1.txt', 'file2.txt']

当我运行代码时,出现了这个错误:
File "C:\Python33\lib\site-packages\sklearn\feature_extraction\text.py", line 195, in <lambda>
return lambda x: strip_accents(x.lower())
AttributeError: '_io.TextIOWrapper' object has no attribute 'lower'

file1.txtfile2.txt 是输入文本文件。我是否使用了错误的格式来定义 text_files?这个错误的原因是什么,我该如何解决这个问题呢?非常感谢您对此提供任何帮助。


这非常令人恼火,因为我在其他地方看到过完全相同(错误的)代码。你可以修复一份副本,但你会想知道,在互联网上还有多少地方存在这个问题? - demongolem
1个回答

12
open(f)是一个_io.TextIOWrapper对象,这就是为什么它失败的原因。
尝试更改。
documents = [open(f) for f in text_files]

documents = [open(f).read() for f in text_files]

返回已经转换的文本(而不是...)。 - SimonT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接