12

输入文本总是菜名列表,其中有 1~3 个形容词和一个名词

输入

thai iced tea
spicy fried chicken
sweet chili pork
thai chicken curry

输出:

thai tea, iced tea
spicy chicken, fried chicken
sweet pork, chili pork
thai chicken, chicken curry, thai curry

基本上,我正在寻找解析句子树并尝试通过将形容词与名词配对来生成二元组。

我想用 spacy 或 nltk 来实现这一点

4

3 回答 3

6

我使用带有英文模型的 spacy 2.0。找到名词和“非名词”来解析输入,然后我将非名词和名词放在一起以创建所需的输出。

您的输入:

s = ["thai iced tea",
"spicy fried chicken",
"sweet chili pork",
"thai chicken curry",]

空间解决方案:

import spacy
nlp = spacy.load('en') # import spacy, load model

def noun_notnoun(phrase):
    doc = nlp(phrase) # create spacy object
    token_not_noun = []
    notnoun_noun_list = []

    for item in doc:
        if item.pos_ != "NOUN": # separate nouns and not nouns
            token_not_noun.append(item.text)
        if item.pos_ == "NOUN":
            noun = item.text

    for notnoun in token_not_noun:
        notnoun_noun_list.append(notnoun + " " + noun)

    return notnoun_noun_list

调用函数:

for phrase in s:
    print(noun_notnoun(phrase))

结果:

['thai tea', 'iced tea']
['spicy chicken', 'fried chicken']
['sweet pork', 'chili pork']
['thai chicken', 'curry chicken']
于 2018-02-16T13:45:16.243 回答
5

使用 NLTK,您可以通过几个步骤实现此目的:

  1. PoS 标记序列

  2. 生成所需的 n-gram(在您的示例中,没有 trigrams,但可以通过 trigrams 生成的skip-grams,然后打出中间标记)

  3. 丢弃所有与模式JJ NN不匹配的 n-gram 。

例子:

def jjnn_pairs(phrase):
    '''
    Iterate over pairs of JJ-NN.
    '''
    tagged = nltk.pos_tag(nltk.word_tokenize(phrase))
    for ngram in ngramise(tagged):
        tokens, tags = zip(*ngram)
        if tags == ('JJ', 'NN'):
            yield tokens

def ngramise(sequence):
    '''
    Iterate over bigrams and 1,2-skip-grams.
    '''
    for bigram in nltk.ngrams(sequence, 2):
        yield bigram
    for trigram in nltk.ngrams(sequence, 3):
        yield trigram[0], trigram[2]

根据您的需要扩展模式('JJ', 'NN')和所需的 n-gram。

我认为没有必要进行解析。然而,这种方法的主要问题是大多数 PoS 标记器可能不会完全按照您想要的方式标记所有内容。例如,我的 NLTK 安装的默认 PoS 标记器将“chili”标记为NN,而不是JJ,并且“fried”得到了VBD。但是,解析不会帮助您!

于 2016-08-31T06:33:30.400 回答
1

像这样的东西:

>>> from nltk import bigrams
>>> text = """thai iced tea
... spicy fried chicken
... sweet chili pork
... thai chicken curry"""
>>> lines = map(str.split, text.split('\n'))
>>> for line in lines:
...     ", ".join([" ".join(bi) for bi in bigrams(line)])
... 
'thai iced, iced tea'
'spicy fried, fried chicken'
'sweet chili, chili pork'
'thai chicken, chicken curry'

或者使用colibricore https://proycon.github.io/colibri-core/doc/#installation ;P

于 2016-08-31T08:52:55.003 回答