在Python中打印词汇定义时出错

1 投票
1 回答
1084 浏览
提问于 2025-04-18 01:44

我在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 个回答

1

问题: 为什么你把Synsets对象当成字符串来用?

在Python中,原生的 string 对象是没有 definition 属性的,它们只有一些基本的功能和属性,具体可以查看这个链接:https://docs.python.org/2/library/string.html

你需要的是来自 NLTKSynset 对象,详细信息可以参考这个链接:http://www.nltk.org/_modules/nltk/corpus/reader/wordnet.html

回到你的代码,你需要一个 key 来访问这些Synsets,比如 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']

然后用这个key把它转换成一个 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).definition() 来获取定义了:

>>> list_of_synsets = [wn.synset(re.findall("'([^']*)'", i)[0]) for i in losis]
>>> for i in list_of_synsets:
...     print i, i.definition()
... 
Synset('bank.n.01') sloping land (especially the slope beside a body of water)
Synset('computer.n.01') a machine for performing calculations automatically
Synset('work.v.02') be employed
Synset('ace.s.01') of the highest quality

撰写回答