【问题标题】:Generate bigrams BUT only noun and verb combinations生成二元组,但只生成名词和动词组合
【发布时间】:2019-08-02 20:02:01
【问题描述】:

下面有一些代码可以为我的数据框列生成二元组。

import nltk
import collections
counts = collections.Counter()
for sent in df["message"]:
    words = nltk.word_tokenize(sent)
    counts.update(nltk.bigrams(words))
counts = {k: v for k, v in counts.items() if v > 25}

这非常适合在我的数据框的“消息”列中生成我最常见的二元组,但是,我想获得每对二元组仅包含一个动词和一个名词的二元组。

任何使用 spaCy 或 nltk 的帮助将不胜感激!

【问题讨论】:

  • 举个例子就好了。
  • @acodejdatam 你的意思是 N, V 和 V, N 双元组吗?
  • @ongenz,是的。我只想要名词动词和动词名词bigrams。

标签: python nlp nltk spacy


【解决方案1】:

使用spaCy,您可以访问各种语言的预训练models。你可以像这样安装它们:python -m spacy download en_core_web_sm

然后,您可以轻松运行类似这样的操作来进行自定义过滤:

import spacy

text = "The sleeping cat thought that sitting in the couch resting would be a great idea."
nlp = spacy.load('en_core_web_sm')
doc = nlp(text)
for i in range(len(doc)):
    j = i+1
    if j < len(doc):
        if (doc[i].pos_ == "NOUN" and doc[j].pos_ == "VERB") or (doc[i].pos_ == "VERB" and doc[j].pos_ == "NOUN"):
            print(doc[i].text, doc[j].text, doc[i].pos_, doc[j].pos_)

哪个会输出

睡猫动词名词

cat think NOUN VERB

couch resting名词动词

【讨论】:

  • 感谢您的帮助!我将如何使用 spaCy 而不仅仅是文本字符串在数据框文本列上运行它?
  • 欢迎您!要在大量文本上有效地运行 spaCy,请使用 nlp.pipe(texts) - 请参阅此处:spacy.io/usage/processing-pipelines#processing
  • Sofie VL 你能提供一个带有数据框的代码示例吗?假设我的数据框中有一列是文本。每一行是一个句子。我如何在上面运行这段代码?我无法通过文档弄清楚。
  • 当然,您必须先从列中提取文本。像text = df["message"] 这样的东西。这不是 spaCy 库的一部分,而是需要在您端进行的预处理......
【解决方案2】:

您必须先应用 pos_tag,然后再应用二元组

你可以这样试试

import nltk

sent = 'The thieves stole the paintings'
token_sent = nltk.word_tokenize(sent)
tagged_sent = nltk.pos_tag(token_sent)

word_tag_pairs = nltk.bigrams(tagged_sent)

##Apply conditions according to your requirement to filter the bigrams

print([(a,b) for a, b in word_tag_pairs if a[1].startswith('N') and b[1].startswith('V')])  

它只是给出一个输出

[(('thieves', 'NNS'), ('stole', 'VBD'))]

【讨论】:

    猜你喜欢
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多