我绝对是初学者。我的解决方案不起作用。我不明白为什么。
fin=open('words.txt')
fin.readline()
for line in fin:
word=line.strip()
def diz():
d={}
for word in line:
d[word]=len(word)
return d
diz()
print(diz())
你的代码几乎可以工作,有几个关键错误。第一个是readline
电话;你没有使用它的返回值,所以它所做的只是跳过单词列表中的第一个单词。其次是如何将单词从for line in fin
循环传递到diz
;只有一个变量line
,当diz
被调用时,它只会在单词列表中保存最后一个单词。第三,line
不是单词列表,而是包含一行的字符串(通常单词列表每行有一个单词(。因此,for word in line
产生最后一行中的所有字母,而不是单词。
我们可以通过稍微移动一下来清理它:
fin=open('words.txt')
d={}
for line in fin:
word=line.strip()
d[word]=len(word)
print(d)
我们可以使它更简洁或通用,但这保留了代码中的关键步骤。
最python的方法是首先阅读这样的单词:
d = {}
with open('words.txt', 'r') as fin:
raw_words = fin.readlines()
for raw_word in raw_words:
word = raw_word.strip()
d[word] = len(word)
# should print the desired dict
print(d)
"with"块为您处理关闭,而for在字典中插入单词及其长度。
我会使用字典理解:
示例文件(单词.txt(:
python
eggs
foo
bar
monthy
法典:
with open('words.txt', 'r') as fwrd:
words = fwrd.readlines()
diz = {wrd.strip(): len(wrd) for wrd in words}
print(diz)
输出:
{'python': 7, 'eggs': 5, 'foo': 4, 'bar': 4, 'monthy': 6}