汉英词典python

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)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二十四桥_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值