gpt4 book ai didi

python - 使用字典的翻译器

转载 作者:行者123 更新时间:2023-11-28 21:36:27 31 4
gpt4 key购买 nike

我正在尝试解决一个可以在 Pieter Spronck 的《The Coder's Apprentice》一书中第 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()

它似乎工作正常,但是当我运行它时,“ Composer ”和“两个”这两个词没有被翻译。

最佳答案

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

关于python - 使用字典的翻译器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50899952/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com