【问题标题】:Using Sklearn's CountVectorizer to find multiple strings not in order使用 Sklearn 的 CountVectorizer 查找多个不按顺序排列的字符串
【发布时间】:2019-03-31 14:00:01
【问题描述】:

CountVectorizer 能否用于识别一组单词是否出现在语料库中,无论顺序如何?

它可以做有序短语:How can I use sklearn CountVectorizer with mutliple strings?

但就我而言,这组单词不会恰好落在每个单词的旁边,因此对整个短语进行标记然后尝试在某些文本文档中查找将导致零查找

我的梦想是让以下事情发生:

import numpy as np
from sklearn import feature_extraction

sentences = [ "The only cool Washington is DC", 
              "A cool city in Washington is Seattle",
              "Moses Lake is the dirtiest water in Washington" ]

listOfStrings = ["Washington DC",
                 "Washington Seattle",  
                 "Washington cool"]

vectorizer = CountVectorizer(vocabulary=listOfStrings)
bagowords = np.matrix(vectorizer.fit_transform(sentences).todense())
bagowords
matrix([[1, 0, 1],
        [0, 1, 1],
        [0, 0, 0],])

实际问题需要更多的词介于两者之间,因此在此处删除停用词不是一个有效的解决方案。任何建议都会很棒!

【问题讨论】:

  • 既然你说的是“不分先后顺序”,那么如果句子中包含“DC代表华盛顿哥伦比亚特区”,它仍然是有效匹配吗?在这里,DC 在华盛顿之前有很多词。
  • 是的,这仍然是一个有效的匹配!

标签: python-3.x scikit-learn sklearn-pandas countvectorizer


【解决方案1】:

正如 cmets 中所讨论的,由于您只想找出文档中是否存在某些单词,因此您需要稍微更改词汇表 (listOfStrings)。

sentences = [ "The only cool Washington is DC", 
              "A cool city in Washington is Seattle",
              "Moses Lake is the dirtiest water in Washington" ]

from sklearn.feature_extraction.text import CountVectorizer
listOfStrings = ["washington", "dc", "seattle", "cool"]
vectorizer = CountVectorizer(vocabulary=listOfStrings,
                             binary=True)   

bagowords = vectorizer.fit_transform(sentences).toarray()

vectorizer.vocabulary
['washington', 'dc', 'seattle', 'cool']

bagowords
array([[1, 1, 0, 1],
       [1, 0, 1, 1],
       [1, 0, 0, 0]])

我已将 binary=True 添加到 CountVectorizer,因为您不想要实际计数,只检查是否存在单词。

bagowords 的输出与您提供的词汇表 (listOfStrings) 的顺序相匹配。所以第一列表示文档中是否存在“washinton”,第二列检查“dc”等等。

当然,您需要注意 CountVectorizer 中可能影响这一点的其他参数。例如:,

  • lowercase 默认为True,所以我在listOfStrings 中使用了小写字母。否则,“DC”、“Dc”、“dc”将被视为单独的词。
  • 您还应该研究token_pattern 参数的效果,默认情况下它只保留长度为2 或更长的字母数字字符串。因此,如果您想检测“a”、“I”等单字母单词,则需要对其进行更改。

希望这会有所帮助。如果有什么不明白的,请随时提问。

【讨论】:

  • 感谢您的输入,但我的目标是找出关键术语列表是否作为一个整体出现在语料库中,而不是单独出现。我喜欢使用 binary=True。我以前是手动做的。但是这种设置方式我不知道西雅图和华盛顿是否出现在一个特定的句子中。当然,对于这个例子,我可以计算出这个,但是对于一个更大的例子,我将无法匹配关键术语列表。关于如何搜索不相邻出现的关键词列表并根据所有这些词是否出现返回 1 或 0 的任何想法?
猜你喜欢
  • 2021-08-29
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
相关资源
最近更新 更多