在python中打印光泽定义时出错

时间:2014-04-07 17:34:33

标签: python nltk wordnet

我在python中有以下同义词列表:

string = ["Synset('bank.n.01')", "Synset('computer.n.01')", "Synset('work.v.02')", "Synset('super.a.01')"]

我试图以下列方式结合个人的光泽度定义:

string1 = ""
for w in string:
     string1 = string1 + w.definition

但它给了我以下错误:

Traceback (most recent call last):
   File "<stdin>", line 2, in <module>
AttributeError: 'str' object has no attribute 'definition'

但如果我这样做

for w in wn.synsets("bank"):
    print w.definition

它成功运行并给出正确的结果。请告诉我该怎么办?

1 个答案:

答案 0 :(得分:1)

问题:为什么将Synsets对象作为字符串?

python中的原生string对象没有definition属性,它们只有这些函数/属性:https://docs.python.org/2/library/string.html

您需要的是来自Synset的{​​{1}}对象,请参阅http://www.nltk.org/_modules/nltk/corpus/reader/wordnet.html

返回到您的代码,您需要NLTK来访问Synsets,例如key

bank.n.01

然后使用密钥将其转换为>>> from nltk.corpus import wordnet as wn >>> import re >>> list_of_synsets_in_str = ["Synset('bank.n.01')", "Synset('computer.n.01')", "Synset('work.v.02')", "Synset('super.a.01')"] >>> losis = list_of_synsets_in_str >>> [re.findall("'([^']*)'", i)[0] for i in losis] ['bank.n.01', 'computer.n.01', 'work.v.02', 'super.a.01'] 对象:

Synset

然后您可以访问>>> [wn.synset(re.findall("'([^']*)'", i)[0]) for i in losis] [Synset('bank.n.01'), Synset('computer.n.01'), Synset('work.v.02'), Synset('ace.s.01')]

中的定义
wn.synset(x).defintion()