簡體   English   中英

如何使用 python 腳本翻譯單詞?

[英]How can I translate words with a python script?

所以我們必須將數字從英語翻譯成德語。 我覺得我做錯了,因為我在測試我的代碼時沒有得到 output。

#!/usr/bin/env python3
import sys

english = sys.stdin.read().split()

num = {}

with open("translation.txt") as f:
    data = f.read().split("\n")

i = 0
while len(data[i]) < 0:
    n = data[i].split()

    n1 = n[0]
    n2 = n[1]
    if n1 not in num:
        num[n1] = n2
    i = i + 1

i = 0
while i < len(english):
    n = english[i]
    if n in num:
        print(num[n])
    i = i + 1

請幫忙。 我什至可以獲得打開文本文件的代碼嗎? 文本文件包含從英語翻譯成德語的數字

翻譯示例.txt

one: eins
two: zwei
three: drei
four: vier
five: funf
six: sechs
seven: sieben
eight: acht
nine: neun
ten: zehn

好吧,您的代碼有一些重大的邏輯錯誤。 首先,循環的比較是錯誤的。 您還拆分了線路,但您離開了:在鍵中。 也不需要檢查這個詞是否已經存在,但我按照你寫的那樣留下了它。 我還添加了兩側翻譯以防萬一您需要它。

這是我對問題的實現:

#!/usr/bin/env python3
import sys

english = sys.stdin.read().split()

num = {}

with open("translation.txt") as f:
    data = f.read().split("\n")

i = 0
while i < len(data):
    n = data[i].split()
    print(n)
    n1 = n[0].replace(':', '')
    n2 = n[1]
    if n1 not in num and n2 not in num:
        num[n1] = n2
        num[n2] = n1
    i = i + 1

print(num['one'])
print(num['eins'])

您通過sys.stdin.read()從標准輸入讀取輸入。 這需要讀取所有字符,直到遇到 EOF,這僅在以下情況下才會發生:

  1. 通過鍵盤輸入 EOF(基於 Unix 的系統為 Ctrl-D,Windows 為 Ctrl-Z);
  2. 輸入從另一個以 EOF 結尾的 stream 重定向,例如文件 stream。

如果通過鍵盤逐行輸入,則在看到 EOF 之前不會看到 output。 如果希望在一行輸入之后立即顯示 output,則應使用input()而不是sys.stdin.read()

@Raguel 的回答中已經解釋了其他問題。

在這里,我們遇到了應用程序邏輯的一個主要問題,正如之前的答案中所提到的:

  • 首先,我們需要加載字典——我們要操作的資源。
  • 其次,我們可以開始翻譯,例如從持續用戶輸入開始逐字翻譯

緊湊型解決方案(需要 python 3.8):

#!/usr/bin/env python3

with open("translation.txt", "r") as f:
    dictionary = { k: v.strip()  for k, v in [line.split(":") for line in f.readlines()]}

while word:=input("Word to translate: "):
    try:
        print(dictionary[word])
    except KeyError:
        print(f"No translation found for the word: {word}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM