簡體   English   中英

在 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() ,您始終可以返回一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'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM