【发布时间】:2021-05-24 16:51:57
【问题描述】:
我的目标是对我从 PDF 中获得 OCRed 的多个 .txt 文档进行词袋分析。我已经使用 nltk 清理了所有 .txt 文档(使所有内容都小写,删除了诸如“the”、“a”等绑定词,并进行了 lammatized 以确保只保留词干)然后我将 .txt 文件保存在 CSV每个文档都有一行,一列是文档名称,然后是每个单词的一列。
- 每一行都有一个带有文件名的单元格,然后是每个单元格中的“帮助”“城镇”等
我现在正在尝试使用 countvectorizer 和 fit_transform 来获取每个变量(单词)用于每行(.txt 文件)的频率的 1 和 0 矩阵。
import pandas as pd
import os
from nltk.tokenize import word_tokenize
file_names = os.listdir(r"C:\Users\erlen\Test 2\test 3")
# Create Dictionary for File Name and Text
file_name_and_text = {}
for file in file_names:
with open(r"C:\Users\Test 2\test 3\\" + file, "r") as target_file:
file_name_and_text[file] = word_tokenize(target_file.read())
file_data = (pd.DataFrame.from_dict(file_name_and_text, orient='index')
.reset_index().rename(index = str, columns = {'index': 'file_name', 0: 'text'}))
file_data.to_csv('LIST OF TEXT.csv', encoding='utf-8', index=False)
# creating the feature matrix
from sklearn.feature_extraction.text import CountVectorizer
matrix = CountVectorizer(max_features=10000, lowercase=False)
X = matrix.fit_transform(file_data).toarray()
#ADD A COLUMN OF 1s to represent YES (target) and NO (non-target)
file_data["investment"] = 1
我尝试了多种解决方案,但都没有成功。这包括将 file_data 转换为: 字符串(文件数据) [文件数据] .fillna("")
还尝试删除 toarray() 但这不是问题
到目前为止,这些都没有奏效,所以有点不知所措。我也查看了数据并将 .txt 文件限制为只有一/两个文件进行测试,因此我可以查看并且我得到相同的错误而没有一个缺失值(当只有一个 .txt 文件时)。
这是我文件的 .head (用同义词替换单词)
<bound method NDFrame.head of file_name text 1 ... 5456 5457 5458
0 test_1.txt face many ... place tool other
我得到的“X = matrix.fit_transform(file_data).toarray()”行的完整错误消息:
Traceback (most recent call last):
File "C:/Users/test file only.py", line 25, in <module>
X = matrix.fit_transform(file_data).toarray()
File "C:\Users\sklearn\feature_extraction\text.py", line 1202, in fit_transform
vocabulary, X = self._count_vocab(raw_documents,
File "C:\Users\sklearn\feature_extraction\text.py", line 1114, in _count_vocab
for feature in analyze(doc):
File "C:\Users\sklearn\feature_extraction\text.py", line 106, in _analyze
doc = tokenizer(doc)
TypeError: expected string or bytes-like object
运行 file_name.dtypes 表示它们都是对象
file_name object
text object
1 object
2 object
3 object
...
5454 object
5455 object
5456 object
5457 object
5458 object
Length: 5460, dtype: object
【问题讨论】:
标签: python machine-learning scikit-learn nltk