gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:27:34 25 4
gpt4 key购买 nike

我在 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

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

最佳答案

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

python中的

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

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

回到您的代码,您需要的是访问同义词集的 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']

然后用 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).defintion()访问定义:

>>> 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

关于python - 在 python 中打印光泽度定义时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22919275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com