8.22 Python IT17:替换词

新手上路,请多包涵

好吧,我一直在努力为学校找出这个 Python 3 编程任务,但我似乎无法让它发挥作用。这里是问题提示

编写一个程序来替换句子中的单词。输入以单词替换对(原始和替换)开头。输入的下一行是替换原始列表中的任何单词的句子。

例如:如果输入是:

汽车 car manufacturer maker children kids 如果汽车还没有儿童座椅,汽车制造商会推荐儿童汽车座椅。

输出是:

如果汽车还没有,汽车制造商会推荐儿童汽车座椅。

您可以假设原始单词是唯一的。

这是我当前的代码/尝试:

 replaceList = input()
a1 = replaceList.split()

sentence = input()
for i in sentence:
    i = int(i)
    output = sentence.replace(a1[i], a1[i+1])
print(output)

原文由 C_Corp2002 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 405
1 个回答

我建议这样(python 3):

 # read first line input
pairs = input().split()

# split to originals and replacements
originals = pairs[::2]
replacements = pairs[1::2]

# read the sentence
sent = input()

# replace all words
for org, repl in zip(originals, replacements):
    sent = sent.replace(org, repl)

# print the new sentence
print(sent)

原文由 Chems Eddine 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏