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

2024-03-29 05:27:02 发布

您现在位置: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)    
        

Tags: oftheindefallspeechreturnsword
2条回答

假设您正在向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'}

相关问题 更多 >