|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
定义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[word])
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[word])
Result2:
ranivorous = frog-eating
rigmarole = nonsense, unnecessary complexity.
谢谢!!!!
- 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
复制代码
|
|