想问道题~谢谢
定义get_dictionary_from_file(filename)函数,该函数将文件名作为参数传递。文件的每一行都包含一个单词,后跟“:”,然后是单词的含义。 “:”始终将单词与其含义分开。示例文件内容为:allegator : someone who alleges.
ecdysiast : an exotic dancer, a stripper.
eructation : a burp, belch.
lickety-split : as fast as possible.
lickspittle : a servile person, a toady.
该函数返回一个字典,其中每个单词都是键,而相应的值就是含义。
注意:键及其对应的值不应包含任何前导或尾随空格(使用strip()方法)。
Test1:
the_dict = get_dictionary_from_file("WordsAndMeanings1.txt")
for word in ["lickspittle", "allegator", "lickety-split"]:
if word in the_dict:
print(word, "=", the_dict)
Result1:
lickspittle = a servile person, a toady.
allegator = some who alleges.
lickety-split = as fast as possible.
Test2:
the_dict = get_dictionary_from_file("WordsAndMeanings2.txt")
for word in ["ranivorous", "cat", "rigmarole"]:
if word in the_dict:
print(word, "=", the_dict)
Result2:
ranivorous = frog-eating
rigmarole = nonsense, unnecessary complexity.
谢谢!!!! def get_dictionary_from_file(filename):
f = open(filename, encoding = "utf-8")
dict1 = {}
for eachline in f:
key, value = eachline.split(":")
dict1 = value.strip()
f.close()
return dict1 冬雪雪冬 发表于 2020-6-4 10:30
emmmm 还是有点错误 不太对 冬雪雪冬 发表于 2020-6-4 10:30
***错误***
追溯(最近一次通话):
<模块>中的文件“ __tester __。python3”,第22行
the_dict = get_dictionary_from_file(“ WordsAndMeanings1.txt”)
在get_dictionary_from_file中的文件“ __tester __。python3”,第5行
键,值= eachline.split(“ \ uff1a”)
ValueError:没有足够的值可解包(预期2,得到1) def get_dicitionary_from_file(file):
result={}
with open (file,'r') as f:
for each_line in f:
word,meaning=each_line.split(':',1) # 用冒号进行切片,只切一次
result.setdefault(word.rstrip().lstrip(),meaning.rstrip().lstrip()) # 去掉前后的空白符,并添加到字典中
return result MIQIWEI 发表于 2020-6-4 10:47
***错误***
追溯(最近一次通话):
中的文件“ __tester __。python3”,第22行
这是切片不成功,很有可能是split的冒号和文件中的冒号不一致。一定要注意中英文标点符号的差异 sunrise085 发表于 2020-6-4 10:49
这是切片不成功,很有可能是split的冒号和文件中的冒号不一致。一定要注意中英文标点符号的差异
嗯嗯 好滴!谢谢!! sunrise085 发表于 2020-6-4 10:47
为什么要用 lstrip().rstrip() 而不是 strip() 呢? MIQIWEI 发表于 2020-6-4 10:47
***错误***
追溯(最近一次通话):
中的文件“ __tester __。python3”,第22行
不要翻译错误信息…… 永恒的蓝色梦想 发表于 2020-6-4 12:24
为什么要用 lstrip().rstrip() 而不是 strip() 呢?
哦,对吼。忘了这个函数了。。。
页:
[1]