python - 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())
因此,似乎以不同的方式处理字符串列表和原始文本字符串列表。由于这是我第一次有意识地遇到这个问题,我将不胜感激了解更多。
解决方案
我向 SKLEARN 开发人员询问了“原始文本文档”的定义。
这是回应:
在文档中,“原始文本文档”是指表示没有预处理的文档的(常规)Python 字符串,语料库是列表(或可迭代的)或此类字符串。所有
CountVectorizer
etc 关心的是它们接收 Python 字符串的列表(或可迭代)。我们说没有“预处理”,因为这些估计器中已经包含了一些预处理,但实际上这个决定取决于用户。
我将为要包含在文档中的完整定义编写 PR。
从原始文档中删除所有西里尔字符后,我的问题中共享的改编代码可以正常工作。
推荐阅读
- python - 每个 ytick 有多个条形的水平条形图
- c++ - 得到 ith,在 O(h) 中,h 是树的高度
- python - 使用 BeautifulSoup 查找 href 链接
- python - 根据单选按钮的一部分打印文本
- javascript - 如何在输入字段中添加必填项并在为空时更改消息错误?
- java - Docker 映像无法将我的 JSON 凭据密钥添加到我的 Google Cloud Natural Language 服务客户端
- amazon-s3 - 如何获得 s3 选择查询以返回单个行
- c - 如何正确释放 SDL_ttf 分配的资源?
- javascript - Exporting interface of redux store state
- php - 告诉文件的扩展名并回显某个值。(PHP/jQuery)