我正在尝试获取大量(~160.000)文档的术语计数的稀疏矩阵。
我清理了文本并希望遍历所有文档(即一次计数向量化一个并附加生成的 1xN 数组。以下代码适用于逐字的情况,但不适用于二元组:
cv1 = sklearn.feature_extraction.text.CountVectorizer(stop_words=None,vocabulary=dictionary1)
cv2 = sklearn.feature_extraction.text.CountVectorizer(stop_words=None,vocabulary=dictionary2)
for row in range(start,end+1):
report_name = fund_reports_table.loc[row, "report_names"]
raw_report = open("F:/EDGAR_ShareholderReports/" + report_name, 'r', encoding="utf8").read()
## word for word
temp = cv1.fit_transform([raw_report]).toarray()
res1 = np.concatenate((res1,temp),axis=0)
## big grams
bigram=set()
sentences = raw_report.split(".")
for line in sentences:
token = nltk.word_tokenize(line)
bigram = bigram.union(set(list(ngrams(token, 2))) )
temp = cv2.fit_transform(list(bigram)).toarray()
res2=np.concatenate((res2,temp),axis=0)
Python 返回
"AttributeError: 'tuple' object has no attribute 'lower'"
大概是因为我将数据输入二元向量化计数器的方式无效。
“raw_report”是一个字符串。单字词典是:
dictionary1 =['word1', 'words2',...]
dictionary2 类似,但基于通过合并所有文档的所有二元组(并保持唯一值,在前面完成)构造的二元组,使得生成的结构是
dictionary2 =[('word1','word2'),('wordn','wordm'),...]
文档二元组具有相同的结构,这就是为什么我很困惑为什么 python 不接受输入。有没有办法解决这个问题,或者我的整个方法不是很pythonic并且开始适得其反?
提前感谢您的帮助!
备注:我知道我可以在更精细的 CountVectorize 命令中完成整个过程(即一步完成清理、标记化和计数),但我更希望自己也能做到这一点(以便查看和存储中间输出) . 此外,鉴于我使用的大量文本,我担心我会遇到内存问题。