在 python 中,我将如何创建一个包含文本文件中列出的所有唯一单词的字典。到目前为止,我有这段代码。谢谢

In python, how would I create a dictionary of all unique words listed in a text file. So far I have this code. Thanks

def getUniqueWords(wordsList) :
    """
    Returns the subset of unique words containing all of the words that are presented in the
    text file and will only contain each word once. This function is case sensitive
    """
    uniqueWords = {}
    for word in speech :
        if word not in speech:
            uniqueWords[word] = []
    uniqueWords[word].append(word)    
        

假设您将一个干净的单词列表传递给 getUniqueWords(),您总是可以 return 列表的 set,由于集合的属性,它会删除重复。

尝试:

def getUniqueWords(wordsList):
  return set(wordsList)

注意:当您键入问题时,您正在使用 markdown,将您的代码括在反引号中,这使得灰色框的格式很好。单个勾号使框内联 like this,三个反勾与顶部的语言一起给出框。

编辑:帮助您发表评论

您可以执行在列表中调用 set() 所执行的操作,但需要手动执行:

wordList = ['b', 'c', 'b', 'a', 'd', 'd', 'f']

def getUniqueWords(wordList):
    unique = set()
    for word in wordList:
        unique.add(word)
    return unique

print(getUniqueWords(wordList))

这就是在 list 上调用 set() 的作用。此外,在开放式问题上不使用内置函数(未指定方法)是对任何问题的愚蠢补充,尤其是 当您使用 python.

text = 'a, a, b, b, b, a'

u = set(text.split(', '))

# u={'a', 'b'}