【问题标题】:Synonyms/Join with a string of words in Python同义词/在 Python 中加入一串单词
【发布时间】: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”,我希望这些都用逗号分隔在一个字符串中

标签: python string join text


【解决方案1】:

如果您的 string 参数来自以空格分隔的单词,您可以试试这个:

def str_synonyms(string):
    newstring_list = []
    for word in string.split():
        if dictionary.synonym(word):
            newstring_list.extend(dictionary.synonym(word))
    newstring = ', '.join(newstring_list)  
    return newstring

【讨论】:

  • 谢谢!当我这样做时,它主要是有效的 - 但由于同义词功能,我最终会遇到与列表/字符串相关的错误。这里有什么想法吗?我已经更新了上面的代码。
  • @user2573355 我已经编辑了答案,现在可以用了吗?
  • 越来越近了!返回此错误:TypeError: cannot concatenate 'str' and 'list' objects
  • #查找搜索词的同义词的功能 def str_synonyms(string): newstring = '' for word in string: if type(dictionary.synonym(word)) == list: newstring += 'none ' else: newstring += str(dictionary.synonym(word)) return newstring
  • @user2573355 我再次编辑了答案,这对我有用。
【解决方案2】:

我查看了从 PyPI 链接的github sources,如果成功,同义词的静态方法似乎返回一个列表,但打印错误并且不返回任何内容 (None)。

我认为这段代码对你有用:

def get_synonym_search(word):

    synlist = dictionary.synonym(word)
    synlist = [] if not synlist else synlist

    synlist = [word] + synlist

    search = "(" + " OR ".join(synlist) + ")"
    return search

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多