我有一个包含不同文本的数组。他们中有些人重复形容词。现在,我想以此为基础,使用1 =文本包含重复形容词和0 =文本不包含重复形容词来表示真值。这是我的文字示例:
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)
答案 0 :(得分:1)
我为您提供了一个解决方案,所以让我们看一下代码中存在的一些错误:
编写list(wn.all_synsets('a')
将返回所有形容词的列表作为Synset对象,但是您真正想要的是形容词名称的字符串。调用synset.name()
将以以下格式返回数据: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)
答案 1 :(得分:1)
如果要获得所有形容词,可能会比较棘手。最好的方法是使用语言解析器,例如斯坦福统计解析器。这将导致句子中每个单词的语法功能。您还可以使用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)
尝试使用以下句子来运行您的方法:“我并不是说你说的那句话”。它失败了,但是使用其他方法却没有成功。原因是“平均”可以是形容词,但并非总是如此。