我试图解决一个问题,这个问题可以在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()
它似乎工作正常,但当我运行它,“作曲家”和“两个”的话没有翻译。你知道吗
您忘记了单词
composers
和单词two
之间的逗号。另外,你写了"composers:componisten"
而不是"composers":"componisten"
。把你的字典改成这样为什么它没有被发现?检查此项:
因为逗号丢失,冒号在字符串中,python将字符串连接起来,创建了一个无用的(但有效的)键/值对。你知道吗
这种行为被记录在案here
相关问题 更多 >
编程相关推荐