【问题标题】:How can I look for specific bigrams in text example - python?如何在文本示例中查找特定的二元组 - python?
【发布时间】:2020-07-20 17:04:27
【问题描述】:

我有兴趣找出一组单词(以 n_grams 为单位)在句子中出现的频率(百分比)。

example_txt= ["order intake is strong for Q4"]

def find_ngrams(text):
    text = re.findall('[A-z]+', text)
    content = [w for w in text if w.lower() in n_grams] # you can calculate %stopwords using "in"
    return round(float(len(content)) / float(len(text)), 5)

#the goal is for the above procedure to work on a pandas datafame, but for now lets use 'text' as an example.
#full_MD['n_grams'] = [find_ngrams(x) for x in list(full_MD.loc[:,'text_no_stopwords'])]

您可以在下面看到两个示例。第一个有效,最后一个无效。

n_grams= ['order']
res = [find_ngrams(x) for x in list(example_txt)]
print(res)
Output:
[0.16667]

n_grams= ['order intake']
res = [find_ngrams(x) for x in list(example_txt)]
print(res)
Output:
[0.0]

如何使 find_ngrams() 函数处理二元组,所以上面的最后一个示例有效?

编辑:还有其他想法吗?

【问题讨论】:

  • 什么是 n_gram ???
  • 这是我感兴趣的单词/单词,以找出它在 example_txt 中被提及的频率。
  • 道歉,我现在添加了一些有问题的解释。

标签: python pandas nlp nltk


【解决方案1】:

线

re.findall('[A-z]+', text)

返回

['order', 'intake', 'is', 'strong', 'for', 'Q'].

因此,字符串“订单摄入”将不会在您的 for here 中匹配:

content = [w for w in text if w.lower() in n_grams]

如果你想让它匹配,你需要从每个 Bigram 中制作一个字符串。

相反,您可能应该使用 this 来查找 Bigram。

对于 N-gram,请查看 this 答案。

【讨论】:

    【解决方案2】:

    也许你已经利用了这个选项,但为什么不使用简单的 .count 结合 len:

    (example_txt[0].count(n_grams[0]) * len(n_grams[0])) / len(example_txt[0]) 
    

    或者,如果您对计算中的空格不感兴趣,您可以使用以下内容:

    (example_txt[0].count(n_grams[0])* len(n_grams[0])) / len(example_txt[0].replace(' ',''))
    

    当然你可以在列表理解中使用它们,这只是为了演示目的


    【讨论】:

    • 有趣的方法。我猜它必须修改什么来查找整个句子,因为它现在正在查看字符。
    • 现在它正在查找给定字符串中的子字符串。 [0] 之所以存在,是因为您使用的句子和字符串示例被放置在一个列表中
    • 我明白了。您的示例代码的结果是 50%,这只有在我们计算字符时才有意义。我们如何让它寻找单词?
    【解决方案3】:

    你可以使用SpaCy Matcher:

    import spacy
    from spacy.matcher import Matcher
    
    nlp = spacy.load("en_core_web_sm")
    matcher = Matcher(nlp.vocab)
    # Add match ID "orderintake" with no callback and one pattern
    pattern = [{"LOWER": "order"}, {"LOWER": "intake"}]
    matcher.add("orderintake", None, pattern)
    
    doc = nlp("order intake is strong for Q4")
    matches = matcher(doc)
    print(len(matches)) #Number of times the bi-gram appears in text
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 2019-03-23
      • 2019-11-16
      相关资源
      最近更新 更多