翻译使用字典

Dan*_*car 2 python dictionary python-3.6

我正在尝试解决一个问题,可以在第13.2.4节中的Pieter Spronck编写的The Coder's Apprentice中找到.这是我到目前为止编写的代码:

english_dutch = {"last":"laatst", "week":"week", "the":"de", "royal":"koninklijk",
    "festival":"feast", "hall":"hal", "saw":"zaag", "first":"eerst", "performance":"optreden",
    "of":"van", "a":"een", "new":"nieuw", "symphony":"symphonie", "by":"bij",
    "one":"een", "world":"wereld", "leading":"leidend", "modern":"modern",
    "composer":"componist", "composers:componisten" "two":"twee", "shed":"schuur", "sheds":"schuren"}

text = "Last week The Royal Festival Hall saw the first \
 performance of a new symphony by one of the world's leading \
 modern composers, Arthur 'Two-Sheds' Jackson."


def clean(t):
    t = t.lower()
    t = t.split()
    new_t = ""
    for word in t:
        new_word = ""
        for letter in word:
            if "a" <= letter <= "z":
                new_word += letter
            if letter == "-":
                new_word += " "
            else:
                continue
        new_t += new_word + " "
    return new_t


def translate(t):
    translation = ""
    for word in t.split():
        if english_dutch.get(word):
            translation += english_dutch[word] + " "
        else:
            translation += word + " "
    return translation


def auto_correct():
    news = ""
    a = translate(clean(text)).split()
    for word in a:
        if len(word) > 1:
            news += word + " "
    print(news)

auto_correct()
Run Code Online (Sandbox Code Playgroud)

它似乎工作正常,但是当我运行它时,"作曲家"和"两个"这两个词并没有被翻译.

yak*_*byd 5

你忘记了单词composers和单词之间的逗号two.另外,你写的是"composers:componisten"代替"composers":"componisten".像这样更改你的字典

 english_dutch = {"last":"laatst", "week":"week",
     "the":"de", "royal":"koninklijk",
     "festival":"feast", "hall":"hal",
     "saw":"zaag", "first":"eerst",
     "performance":"optreden",
     "of":"van", "a":"een",
     "new":"nieuw", "symphony":"symphonie",
     "by":"bij",
     "one":"een", "world":"wereld",
     "leading":"leidend", "modern":"modern",
     "composer":"componist",
     "composers":"componisten", "two":"twee",  # <- HERE
     "shed":"schuur", "sheds":"schuren"}
Run Code Online (Sandbox Code Playgroud)

它未被发现的原因?检查一下:

>>> {"composers:componisten" "two":"twee"}
{'composers:componistentwo': 'twee'}
Run Code Online (Sandbox Code Playgroud)

因为逗号丢失且冒号字符串中,所以python连接了字符串,创建了一个无用(但有效)的键/值对.

此行为记录在此处

允许使用多个相邻的字符串文字(由空格分隔),可能使用不同的引用约定,并且它们的含义与它们的连接相同.因此,"你好"'世界'相当于"helloworld".