翻译人员使用词典

2024-05-29 04:31:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图解决一个问题,这个问题可以在Pieter Spronck的《程序员的学徒》一书的13.2.4节中找到。这是我到目前为止写的代码:

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()

它似乎工作正常,但当我运行它,“作曲家”和“两个”的话没有翻译。你知道吗


Tags: oftheinnewforifenglishdef
1条回答
网友
1楼 · 发布于 2024-05-29 04:31:33

您忘记了单词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"}

为什么它没有被发现?检查此项:

>>> {"composers:componisten" "two":"twee"}
{'composers:componistentwo': 'twee'}

因为逗号丢失,冒号在字符串中,python将字符串连接起来,创建了一个无用的(但有效的)键/值对。你知道吗

这种行为被记录在案here

Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld".

相关问题 更多 >

    热门问题