【问题标题】:How do input more than one word for translation in Python?Python中如何输入多个单词进行翻译?
【发布时间】:2019-06-17 14:07:26
【问题描述】:

我正在尝试制作一个愚蠢的翻译游戏作为练习。我将“Ben”替换为“Idiot”,但它仅在我输入的唯一单词是“Ben”时才有效。如果我输入“你好,本”,那么控制台会打印出一个空白语句。我试图得到“你好,白痴”。或者,如果我输入“嗨,本!”我想得到“你好,白痴!”。如果我输入“Ben”,那么它会转换为“Idiot”,但只有在输入名称本身时。

我正在使用 Python 3 并且正在使用函数 def translate(word): 所以也许我过于复杂了这个过程。

def translate(word):
translation = ""
if word == "Ben":
    translation = translation + "Idiot"

return translation


print(translate(input("Enter a phrase: ")))

如果我解释了所有这些奇怪的事情,我很抱歉。对编码和使用本网站完全陌生!感谢所有帮助!

【问题讨论】:

  • 已经给出了答案,所以我只想补充一点,您当前的检查仅在 Ben 是控制台中唯一的字符串输入时才有效。如果您想检查Ben 是否在用户输入的短语中,您可能更喜欢if "Ben" in word

标签: python python-3.x python-2.7


【解决方案1】:

为此使用str.replace() 函数:

sentence = "Hi there Ben!"
sentence=sentence.replace("Ben","Idiot")
Output: Hi there Idiot!
#str.replace() is case sensitive 

【讨论】:

    【解决方案2】:

    首先,您必须将字符串拆分为单词:

    s.split()
    

    但是那个函数,通过white spaces将字符串拆分为单词,还不够好!

    s = "Hello Ben!"
    print(s.split())
    
    Out: ["Hello", "Ben!"]
    

    在这个例子中,你不能轻易找到“Ben”。 在这种情况下,我们使用re

    re.split('[^a-zA-Z]', word)
    
    Out: ["Hello", "Ben", ""]
    

    但是,我们错过了“!”,我们改变它:

    re.split('([^a-zA-Z])', word)
    
    Out: ['Hello', ' ', 'Ben', '!', '']
    

    最后:

    重新导入

    def translate(word):
        words_list = re.split('([^a-zA-Z])', word)
        translation = ""
        for item in words_list:
            if item == "Ben":
                translation += "Idiot"
            else:
                translation += item
    
        return translation
    
    
    print(translate("Hello Ben! Benchmark is ok!"))
    

    附注:

    如果我们使用replace,我们的答案是错误的!

    "Hello Ben! Benchmark is ok!".replace("Ben", "Idiot")
    
    Out: Hello Idiot! Idiotchmark is ok!
    

    【讨论】:

      猜你喜欢
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多