我正在研究一段簡單的代碼,它需要一個文本文件,並將字典中的鍵分配爲英文字母az中的每個字母,並且以該字母開頭的每個單詞都作爲一個集合分配給該鍵。我知道這樣做肯定會有更多的「pythonic」方式嗎?在字典中指定小寫字母作爲鍵?
# P8.11 : This program builds a dictionary of sets from a text file of words.
# The keys are a letter, and the values are a set of words that start with that
# letter.
def main():
wordList = set()
inFile = open("words.txt", "r")
for line in inFile:
line = line.rstrip()
line = line.lower()
wordList = line.split()
print(buildDict(wordList))
print(wordList)
def buildDict(wordList):
wordDict = dict()
for word in wordList:
if word.startswith("a"):
wordDict["a"] = word
if word.startswith("b"):
wordDict["b"] = word
if word.startswith("c"):
wordDict["c"] = word
if word.startswith("d"):
wordDict["d"] = word
if word.startswith("e"):
wordDict["e"] = word
if word.startswith("f"):
wordDict["f"] = word
if word.startswith("g"):
wordDict["g"] = word
if word.startswith("h"):
wordDict["h"] = word
if word.startswith("i"):
wordDict["i"] = word
return wordDict
+1對於偉大的重構 - 你可能想要再次警惕零長度的單詞。 :) – 2014-11-01 19:35:44
@MariaZverina這是一個好主意,但我認爲假設正確的輸入可能是正確的,以保持答案的簡潔性和與問題的相關性。 – 2014-11-01 19:36:54