import string
def read_to_dic(filename):
"""读文件每行根据空格切分一次,作为字典的键和值添加到字典中。
返回一个字典类型。
"""
my_dic = {}
with open(filename, 'r', encoding='utf-8') as data:
for x in data:
x = x.strip().split(maxsplit=1)
my_dic.update({x[0]: x[1]})
return my_dic
def sentence_to_lst(sentence):
"""将句子里的's 用 is 替换,n't 用 not 替换。
所有符号替换为空格,再根据空格切分为列表。
返回列表。
"""
sentence = sentence.replace("n't", ' not')
sentence = sentence.replace("'s", ' is')
for x in string.punctuation:
sentence = sentence.replace(x, ' ')
sentence_lst = sentence.split()
return sentence_lst
def query_words(sentence_lst, my_dic):
"""接收列表和字典为参数,对列表中的单词进行遍历,
将单词字母转小写,到字典中查询单词的中文意义并输出。
若单词在字典中不存在,输出'自己猜'。
"""
for word in sentence_lst:
word = word.lower()
print(word, my_dic.get(word, '自己猜'))
if __name__ == '__main__':
my_str = input()
file = 'dicts.txt'
dic = read_to_dic(file)
lst = sentence_to_lst(my_str)
query_words(lst, dic)
汉英词典python
最新推荐文章于 2023-04-15 11:17:05 发布