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


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(),您总是可以返回该列表的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'}

最新更新