【发布时间】:2016-01-31 17:40:19
【问题描述】:
我想使用 PyDictionary 查找文本字符串中每个单词的所有同义词,并且我想返回字符串中每个单词的答案的串联版本。我知道我需要某种加入声明,但还没有完全解决。到目前为止,答案通常很有帮助,但还有一个额外的问题。
当 dictionary.synonyms(word) 没有任何同义词时,它会回复“word has no Synonyms in API”,它认为这是一个列表。我收到此错误:
<ipython-input-53-9f48f79fe623> in str_synonyms(string)
3 newstring = ''
4 for word in string:
5 while dictionary.synonym(word).endswith("has no Synonyms in the API"):
6 newstring += 'none'
7 else:
当我添加过滤器以将这些实例替换为“无”时。
这是函数的最新迭代:
#Function to find synonyms for search terms
def str_synonyms(string):
newstring = ''
for word in string:
while dictionary.synonym(word).endswith("has no Synonyms in the API"):
newstrong += none
else:
newstring += dictionary.synonym(word)
return newstring
感谢任何额外的帮助,谢谢!
【问题讨论】:
-
你没有正确使用
join函数,提醒str.join(list)返回一个字符串,其中list中的每个值由str连接在一起 -
dictionary.synonym(word)返回一个 list (我猜是word的所有可能同义词)。那么,如果有多个同义词,您想在newstring后面附加什么? (顺便说一句,这解释了TypeError异常)。 -
我想附加所有的同义词。所以如果淋浴的同义词是“rain”、“downpour”和“flood”,我希望这些都用逗号分隔在一个字符串中