输入文本始终是菜名列表,其中有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来实现这一点。
发布于 2018-02-16 21:45:16
我使用的是spacy 2.0和英语模式。为了找到名词和“非名词”来解析输入,然后我将非名词和名词组合在一起以创建所需的输出。
您的输入:
s = ["thai iced tea",
"spicy fried chicken",
"sweet chili pork",
"thai chicken curry",]Spacy解决方案:
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']发布于 2016-08-31 14:33:30
使用NLTK只需几个步骤即可完成此操作:
sequences
示例:
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元语法。
我认为没有必要进行解析。然而,这种方法的主要问题是,大多数PoS标记器可能不会完全按照您想要的方式标记所有内容。例如,我的NLTK安装的默认PoS标记器将"chili“标记为NN,而不是JJ,而将"fried”标记为VBD。不过,解析并不能帮助你解决这个问题!
发布于 2016-08-31 16:52:55
如下所示:
>>> 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
https://stackoverflow.com/questions/39241709
复制相似问题