【发布时间】:2014-11-01 15:05:41
【问题描述】:
我正在编写一段简单的代码,该代码采用文本文件,并将 dict 中的键分配为英文字母 a-z 中的每个字母,并且以该字母开头的每个单词都分配给键作为放。我知道必须有一种更“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
【问题讨论】:
标签: python dictionary set python-3.4