【发布时间】:2017-09-20 19:55:25
【问题描述】:
问题/我尝试了什么
我下载了我尝试运行的 textmining 1.0 库,但是这给了我一些导入错误(因为这是一个 python 2 库)所以我在 stackoverflow 上搜索并发现我必须使用 2to3.py 现在一切正常。但是,当我这样做时:
def buildMatrix(self,document_list):
print("building matrix...")
tdm = textmining.TermDocumentMatrix()
for doc in document_list:
tdm.add_doc(doc)
tdm.write_csv(r'path\matrix.csv', cutoff=2)
(document_list 只是strings 的列表)
我收到以下错误:
File "C:\Users\RICK\Anaconda\lib\site-packages\textmining\__init__.py", line 335, in write_csv
f.writerow(row)
TypeError: a bytes-like object is required, not 'str'
在检查textmining 1.0 的代码时,我很确定该行应该是string。所以我想通过编辑源代码来打印这一行:
f = csv.writer(open(filename, 'wb'))
for row in self.rows(cutoff=cutoff):
print(row)
f.writerow(row)
但是即使现在我得到相同的TypeError:
File "C:\Users\RICK\Anaconda\lib\site-packages\textmining\__init__.py", line 335, in write_csv
print(row)
TypeError: a bytes-like object is required, not 'str'
我搜索堆栈溢出以通过将 'wb' 替换为 'w' 来解决此问题,但这仍然给了我 TypeError.
问题
- 如何修复代码以使其能够写入行。
- 为什么连打印语句都会导致
TypeError
根据评论编辑:
克劳迪奥的建议还是给了我TypeError:
File "C:\Users\RICK\Anaconda\lib\site-packages\textmining\__init__.py", line 335, in write_csv
f.write(row)
TypeError: a bytes-like object is required, not 'str'
托尼的建议:
代码检查:
for article in articles:
abstract = searcher.getArticleAbstract(article)
print(type(abstract)) #--> returns <class 'str'>
all_abstracts.append(abstract)
txtSearcher.buildMatrix(all_abstracts)
我现在有这些open 行:
f = open(os.path.join(data_dir, 'stopwords.txt'),"r")
f = open(os.path.join(data_dir, 'dictionary.txt'),"r")
f = csv.writer(open(filename, 'w'))
发生了一些奇怪的事情
def write_csv(self, filename, cutoff=2):
print("This really makes me sad!")
"""
Write term-document matrix to a CSV file.
filename is the name of the output file (e.g. 'mymatrix.csv').
cutoff is an integer that specifies only words which appear in
'cutoff' or more documents should be written out as columns in
the matrix.
"""
print(self.rows)
f = csv.writer(open(filename, 'w'))
for row in self.rows(cutoff=cutoff):
f.writerow(row)
它确实打印了“构建矩阵..”(因此调用了该函数)但是它不打印print("This really makes me sad!")
【问题讨论】:
-
在 Python 3 中,您应该使用带有 csv writer 的文本模式,以及
newline=''。至于为什么print()会出现同样的错误,是不是被什么东西遮住了?
标签: python csv export-to-csv text-mining