首页 > 解决方案 > Python中原始文本字符串列表和字符串列表之间的关系

问题描述

阅读使用 SKLEARN进行标记化的文档,我想知道为什么Python中的字符串列表和原始文本字符串列表之间显然存在差异。

SKLEARN 文档提供了以下示例,该示例运行良好:

from sklearn.feature_extraction.text import CountVectorizer
corpus = ['This is the first document.', 'This document is the second document.', 'And this is the third one.', 'Is this the first document?']
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names())

输出是:

['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']

但是,如果您从 .txt 文件中将文本作为字符串读取,并将其定义为corpus,则错误通知为:

ValueError: Iterable over raw text documents expected, string object received.

corpus然而,SKLEARN 示例中的实际类型是<class 'list'>.

将 .txt 文件中的字符串写入列表并摄取它们会再次触发,ValueError但同时会给我一个令牌列表。

调整后的代码为:

import string
from sklearn.feature_extraction.text import CountVectorizer
import nltk
from nltk.corpus import stopwords

text_file=open("[path]\\[file].txt", "r", encoding="latin1")
words=text_file.read() # reads file as string
corpus=[words] # turn string into list
print(type(corpus)) # retrieves: <class 'list'>

# tokenize text

vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names())

因此,似乎以不同的方式处理字符串列表和原始文本字符串列表。由于这是我第一次有意识地遇到这个问题,我将不胜感激了解更多。

标签: pythonstringscikit-learn

解决方案


我向 SKLEARN 开发人员询问了“原始文本文档”的定义。

这是回应

在文档中,“原始文本文档”是指表示没有预处理的文档的(常规)Python 字符串,语料库是列表(或可迭代的)或此类字符串。所有CountVectorizeretc 关心的是它们接收 Python 字符串的列表(或可迭代)。我们说没有“预处理”,因为这些估计器中已经包含了一些预处理,但实际上这个决定取决于用户。

我将为要包含在文档中的完整定义编写 PR。

从原始文档中删除所有西里尔字符后,我的问题中共享的改编代码可以正常工作。


推荐阅读