【发布时间】:2018-07-20 17:24:41
【问题描述】:
我正在尝试测试将数据从 csv 文件加载到 TextBlob 以创建分类器,然后我将使用训练集对其进行测试。我从一个小的 csv 开始,只是为了测试它并确保它工作,然后再为真实的东西写数百行。但是,我遇到了一个问题。我正在使用 TextBlob 网站上列出的示例代码:
from textblob.classifiers import NaiveBayesClassifier
with open('testerdict.csv',) as fp:
cl = NaiveBayesClassifier(fp, format="csv")
test = [
('The beer was good.', 'pos'),
('I do not enjoy my job', 'neg'),
("I ain't feeling dandy today.", 'neg'),
("I feel amazing!", 'pos'),
('Gary is a friend of mine.', 'pos'),
("I can't believe I'm doing this.", 'neg')
]
cl = NaiveBayesClassifier(fp)
print(cl.classify("This is an amazing library!"))
print(cl.accuracy(test))
我收到的错误取决于我格式化 csv 文件的方式,所以我认为问题出在那儿。如果我这样格式化:
我收到此错误:ValueError: I/O operation on closed file.
如果我这样格式化:
我收到此错误:ValueError: not enough values to unpack (expected 2, got 1)
就像我说的那样,我刚刚制作了一个非常快速且基本的 csv,因此我可以了解如何正确格式化并将其加载到 TextBlob 中以用于分类器的训练数据。有没有人对可能出现的问题有任何想法?
提前致谢。
编辑:根据要求进行完整追溯:
File "C:\Users\Ver\AppData\Local\Programs\Python\Python36-32\SA Project\Work\tester.py", line 14, in <module>
cl = NaiveBayesClassifier(fp)
File "C:\Users\Ver\AppData\Local\Programs\Python\Python36-32\lib\site-packages\textblob\classifiers.py", line 205, in __init__
super(NLTKClassifier, self).__init__(train_set, feature_extractor, format, **kwargs)
File "C:\Users\Ver\AppData\Local\Programs\Python\Python36-32\lib\site-packages\textblob\classifiers.py", line 136, in __init__
self.train_set = self._read_data(train_set, format)
File "C:\Users\Ver\AppData\Local\Programs\Python\Python36-32\lib\site-packages\textblob\classifiers.py", line 148, in _read_data
format_class = formats.detect(dataset)
File "C:\Users\Ver\AppData\Local\Programs\Python\Python36-32\lib\site-packages\textblob\formats.py", line 145, in detect
if Format.detect(fp.read(max_read)):
ValueError: I/O operation on closed file.
【问题讨论】:
-
请包含其中一种方法的完整回溯
-
按要求完成。
-
在 猜测 时,缩进
cl = NaiveBayesClassifier(fp)以与cl = NaiveBayesClassifier(fp, format="csv")保持一致。编辑:实际上这并不像我最初想象的那样猜测。cl = NaiveBayesClassifier(fp)在with块之外,它的具体职责是在您离开其范围后关闭文件。 -
如果我包含一些在不加载 csv 文件的情况下正常运行的演示代码,也许它可能有用?我现在将其放入,以便人们了解所需的格式。
-
不,我想我已经解决了这个问题。你试过我的建议了吗?您还必须缩进
test