[英]How to index input words that has more than one word per line in Python
[英]How do input more than one word for translation in Python?
我正在嘗試將愚蠢的翻譯游戲作為練習。 我用“白痴”取代“本”,但只有當我輸入的唯一單詞是“Ben”時它才有效。 如果我輸入“Hello,Ben”,則控制台會打印出一個空白語句。 我想要“你好,白痴”。 或者,如果我輸入“你好,Ben!” 我想要“你好白痴!”。 如果我輸入“Ben”,則它會轉換為“Idiot”,但僅在輸入名稱時才會轉換為“Idiot”。
我正在使用Python 3並使用函數def translate(word):所以也許我過度復雜化了這個過程。
def translate(word):
translation = ""
if word == "Ben":
translation = translation + "Idiot"
return translation
print(translate(input("Enter a phrase: ")))
如果我解釋這一切都很奇怪,我很抱歉。 完全是編碼和使用本網站的新手! 感謝所有的幫助!
使用str.replace()
函數:
sentence = "Hi there Ben!"
sentence=sentence.replace("Ben","Idiot")
Output: Hi there Idiot!
#str.replace() is case sensitive
首先,您必須將字符串拆分為單詞:
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!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.