对于我的comp sci课程,我被指派制作英语到海盗字典。提示用户输入一个句子,然后将其翻译成盗版,但它不起作用,我不知道为什么。任何帮助将不胜感激。
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate: ")
for x in range(len(a)):
b = a.replace(x, eng2pir[x])
print(b)
答案 0 :(得分:1)
你的循环正在迭代x
,因此.replace()
将为输入中的每个字符取整数值。这有几个原因:
最后,请注意{{1}}替换字符串中搜索项的第一次出现。要以仍然使用该方法的方式修改此问题的方法,请考虑以下两个主要更改:
答案 1 :(得分:0)
你正在迭代字符串输入中的每个字符,正如之前的另一个答案所说,replace
只替换了第一次出现。
你想做这样的事情(在你制作完字典之后)。
a = input("Please enter a sentence to be translated into pirate: ")
for x in eng2pir:
while x in a:
a = a.replace(x,eng2pir[x])
print(a)
答案 2 :(得分:0)
表示范围内的x(len(a)): b = a.replace(x,eng2pir [x])
因为for循环x是int 但是eng2pir dict no int key
输出错误
#!/usr/bin/env python
# coding:utf-8
'''黄哥Python'''
eng2pir = {}
eng2pir['sir'] = 'matey'
eng2pir['hotel'] = 'fleabag inn'
eng2pir['restauraunt'] = 'galley'
eng2pir['your'] = 'yer'
eng2pir['hello'] = 'avast'
eng2pir['is'] = 'be'
eng2pir['professor'] = 'foul blaggart'
a = input("Please enter a sentence to be translated into pirate:\n ")
lst = a.split()
b = ''
for word in lst:
b += eng2pir.get(word, "")
print(b)