同义词/用Python中的一串单词加入

时间:2016-01-31 17:40:20

标签: python string join text

我想使用PyDictionary来查找文本字符串中每个单词的所有同义词,并且我想为字符串中的每个单词返回连接的连接版本。我知道我需要某种加入声明,但还没有完全解决。到目前为止,答案一般都有帮助,但还有一个复杂的问题。

当dictionary.synonyms(word)没有任何同义词时,它会回复“它在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:

当我添加过滤器以用“none”替换这些实例时。

这是函数的最新版本:

 #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

感谢任何其他帮助,谢谢!

2 个答案:

答案 0 :(得分:2)

如果您的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

答案 1 :(得分:0)

我看了一下从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