汉英词典python

汉英词典python,第1张

汉英词典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)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5711769.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存