Python英汉词典查询
英汉词典
类型:字典
描述
你从武汉搬到美国生活,这里的人都讲英语,你的英语不好,好在你有一个程序,可以把英语译成中文,帮助你与人沟通。
(注意:词典文件没有精校,存在部分格式不一致的问题,处理时根据空格切分一次,只把英文和中文解释切分开。)
输入
输入一个英文句子
输出
输出英文句子中每个单词的中文意思,每行一个单词,单词字母转小写,“'s
” 用 " is
"替换,“n't
” 用" not
" 替换(替换为空格加is或not),单词与意义间用空格分隔,当查询的词在文件中不存在时,输出’自己猜
’
示例 1
输入:
For others, but to live for yourself.
输出:
for 给,作...用的
others 自己猜
but 但是,除了
to 向,到
live 居住,生存 活的
for 给,作...用的
yourself 你(们)自己
参考代码
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)
作者:m0_62488776