python - CountVectorizer 返回零
问题描述
我有一个词汇文本文件,其中每一行都是一个单词。词汇表中的几个单词如下所示:
AccountsAndTransactions_/get/v2/accounts/details_DELETE
AccountsAndTransactions_/get/v2/accounts/details_GET
AccountsAndTransactions_/get/v2/accounts/details_POST
AccountsAndTransactions_/get/v2/accounts/{accountId}/transactions_DELETE
AccountsAndTransactions_/get/v2/accounts/{accountId}/transactions_GET
AccountsAndTransactions_/get/v2/accounts/{accountId}/transactions_POST
重要提示:AccountsAndTransactions_/get/v2/accounts/details_DELETE
这是本题中的一个词。
从文本文件中读取词汇:
with open(Path(VOCAB_FILE), "r") as f:
vocab = f.read().splitlines()
生成doc_paths
:
doc_paths = [f for f in listdir(DOC_DIR) if isfile(join(DOC_DIR, f))]
r = re.compile(".*txt")
doc_paths = list(filter(r.match, doc_paths))
doc_paths = [Path(join(DOC_DIR, i)) for i in doc_paths]
我正在CountVectorizer
处理文件。
tf_vectorizer = CountVectorizer(input='filename', lowercase=False, vocabulary=vocab)
tf = tf_vectorizer.fit_transform(doc_paths) # doc_paths is list of pathlib.Path(...) object.
X = tf.toarray() # returns zero matrix
问题是所有值X
都为零。(语料库文档不为空。)
有人可以帮助我吗?我想要每个文档的词汇表中每个单词的词频。
解决方案
我通过覆盖默认值解决了这个analyzer
问题CountVectorizer
:
def analyzer_custom(doc):
return doc.split()
tf_vectorizer = CountVectorizer(input='filename',
lowercase=False,
vocabulary=vocab,
analyzer=analyzer_custom)
感谢@Chris 解释了 CountVectorizer 的内部细节。
推荐阅读
- sql - Oracle SQL 过滤正常值中的高值
- ios - 如何在 Xcode 11.4 中将 Swift 3 更改为 4
- amazon-ses - 雅虎拒绝来自 Amazon SES 的邮件并出现 SPF 失败错误,但还在 DMARC 报告中显示 SPF 通过
- javascript - 如何将返回值存储在组件道具vue js中
- marklogic - 如何在 ml-gradle 中配置多个 REST API 服务器?
- php - 我正在使用 Cpanel UAPI,但每当我使用此 api 时,它都会返回一个错误,即无法在电子邮件类别中找到 get_lists_total_disk_usage
- python - 如何在模板中显示存储在 django 数据库中的 youtube url
- webpack - 点燃元素 | 无法将 scss 加载到 lit-element
- python - 神经网络多类分类器会自动做 argmax 吗?
- ios - 如何使用 UITextFields 在同一视图控制器中使用多个 UIPickerViews