关闭

translate, dictionary demo

865人阅读 评论(0) 收藏 举报
分类:
#quote from MIT 'introduction to computation and programming using python, Revised'
EtoF = {'bread':'pain', 'wine':'vin', 'with':'avec', 'I':'Je',
        'eat':'manage', 'drink':'bois', 'John':'Jean',
        'friends':'amis', 'and':'et', 'of':'du', 'red':'rouge'}
FtoE = {'pain':'bread', 'vin':'wine', 'avec':'with', 'Je':'I',
        'mange':'eat', 'bois':'drink', 'Jean':'John',
        'amis':'friends', 'et':'and', 'du':'of', 'rouge':'red'}
dicts = {'English to French':EtoF, 'French to English':FtoE}

def translateWord(word, dictionary):
    if word in dictionary.keys():
        return dictionary[word]
    elif word != '':
        return '"' + word + '"'
    return word
    
def translate(phrase, dicts, direction):
    UCLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    LCLetters = 'abcdefghijklmnopqrstuvwxyz'
    letters = UCLetters + LCLetters
    dictionary = dicts[direction]
    translation = ''
    word = ''
    for c in phrase:
        if c in letters:
            word += c
        else:
            translation += translateWord(word, dictionary) + c
            word = ''
    return translation + ' ' + translateWord(word, dictionary)
    
print translate('I drink good red wine, and eat bread.',
                 dicts, 'English to French')
print translate('Je bois du vin rouge.',
                 dicts, 'French to English')
                 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:91337次
    • 积分:2930
    • 等级:
    • 排名:第12493名
    • 原创:165篇
    • 转载:108篇
    • 译文:30篇
    • 评论:1条
    文章分类
    最新评论