CountVectorizer fit_transform error: TypeError: expected string or bytes-like object

CountVectorizer fit_transform error: TypeError: expected string or bytes-like object

我的目标是 运行 对我从 PDF 进行 OCR 识别的多个 .txt 文档进行词袋分析。我已经使用 nltk 清理了所有 .txt 文档(将所有内容设为小写,删除了诸如“the”、“a”等绑定词,并进行了语法化以确保只保留词干)然后我将 .txt 文件保存在 CSV 中每个文档一行,一列包含文档名称,然后一列用于每个单独的单词。

我现在正在尝试使用 countvectorizer 和 fit_transform 来获得一个由 1 和 0 组成的矩阵,表示每个变量(单词)在每一行(.txt 文件)中的使用频率。

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 转换为: 海峡(file_data) [file_data] .fillna("")

也试过删除 toarray() 但这不是问题所在

None 到目前为止,其中的一些已经奏效了,但有点不知道问题是什么。我也查看了数据并将 .txt 文件限制为仅 one/two 文件进行测试,这样我就可以查看并得到相同的错误而没有一个缺失值(当只有一个 .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

运行ning 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

所以我最终找到了这个问题的解决方案(或至少是解决方法)。我没有先将文件导入 pandas 帧,而是直接通过 CountVectorizer 函数导入它们:

# creating the feature matrix
from sklearn.feature_extraction.text import CountVectorizer
matrix = CountVectorizer(input = 'filename', max_features=10000, lowercase=False)
feature_variables = matrix.fit_transform(file_locations).toarray()

我不是 100% 确定原始问题是什么,但希望这可以帮助遇到类似问题的任何人。请注意,此确切代码要求文件位于 运行 文件夹中的 .py 文件中。但这很容易改变。

如果不是,我怀疑可能是因为 pandas 和 numpy 数据帧和命令之间存在差异。