从重复的形容词中获取真值

Get truth values out of repeating adjectives

我有一个包含不同文本的数组。其中一些有重复的形容词。现在我想用它做一个数组,它包含真值 1 = text 包含一个重复的形容词,0 = text 不包含一个重复的形容词。这是我的文本示例:

text = (['When someone who is extremely selfish dramatically
 wonders why people are so selfish !', 'I asked God to 
protect me from my enemies .. shortly after I started losing friends'])

到目前为止,我尝试使用 wordnet 获取单词的类型

from nltk.corpus import wordnet as wn

my_list = []
for synset in list(wn.all_synsets('a')):
    my_list.append(synset)
my_list

truth_values = []
for sentence in text:
    for word in sentence:
        if word in my_list:
            truth_values.append(1)
from nltk.corpus import wordnet as wn

此代码出现以下错误:

'str' object has no attribute '_name'

对于重复条件,我想到了一个像

这样的计数器
if counter >=1:
    truth_value.append(1)

我有适合您的解决方案,所以让我们来看看您的代码中存在的一些错误:

list(wn.all_synsets('a')会return一个所有形容词的列表作为Synset对象,但你真正想要的是形容词名称的字符串。以这种格式调用 synset.name() returns 数据:acroscopic.a.01。因为我们只想要它的第一部分(并且作为一个字符串),我们将更改

for synset in list(wn.all_synsets('a')):
    my_list.append(synset)

for synset in list(wn.all_synsets('a')):
    my_list.append(str(synset.name()).split(".")[0])

现在我们有了所需的所有形容词列表。现在,请注意行

for word in sentence:

正在解析句子中的单个字符而不是单词。我们要的是

for word in sentence.split(" "):

综上所述,这是我解决这个问题的方法:

truth_values = []
for sentence in text:
    adjectives = []
    for word in sentence.split(" "):
        if word in my_list:
            adjectives.append(word)
    truth_values.append(1 if any(adjectives.count(adj) > 1 for adj in adjectives) else 0)

如果你想得到所有的形容词,可能有点棘手。最好的方法是使用语言解析器,例如斯坦福统计解析器。它将导致句子中每个单词的语法功能。你也可以使用 spacy.

import spacy

# Load English tokenizer, tagger, parser, NER and word vectors
nlp = spacy.load("en_core_web_sm")

# Process whole documents
text = ("When someone who is extremely selfish dramatically"
        "wonders why people are so selfish !")
doc = nlp(text)

# Analyze syntax
adj = [token.lemma_ for token in doc if token.pos_ == "ADJ"]
repeat = len(adj) != len(set(adj))
print("Adjectives:", adj)
print("Repeats?", repeat)

尝试 运行 你用句子的方法:"I didn't mean what you mean when you say that"。它失败了,但是使用另一种方法却没有。原因是'mean' 可以做形容词,但不总是这样。