【问题标题】:zyBooks Lab Activity 6.19 - Replacement WordszyBooks Lab Activity 6.19 - 替换词
【发布时间】:2022-06-19 06:13:47
【问题描述】:

我的输出有问题。 我很确定这是我的打印语句或我的句子。替换编码。

这是我的代码:

word_pairs = {}

tokens = input().split()
sentence = input()

step = 2
for index in range(0,len(tokens), step):
    key = tokens[index]
    value = tokens[index+1]
    
    word_pairs[key] = value
    for original, new in word_pairs.items():
        sentence = sentence.replace(original, new)
        
        print(sentence)

这里是示例输入:

automobile car   manufacturer maker   children kids

The automobile manufacturer recommends car seats for children if the automobile doesn't already have one.

预期输出:

The car maker recommends car seats for kids if the car doesn't already have one. 

我的输出:

The car manufacturer recommends car seats for children if the car doesn't already have one.
The car manufacturer recommends car seats for children if the car doesn't already have one.
The car maker recommends car seats for children if the car doesn't already have one.
The car maker recommends car seats for children if the car doesn't already have one.
The car maker recommends car seats for children if the car doesn't already have one.
The car maker recommends car seats for kids if the car doesn't already have one.

【问题讨论】:

  • 在所有替换完成后的 for 循环之后打印。此外,第二个 for 循环应该在第一个之后,而不是在第一个之后。

标签: python


【解决方案1】:

对不起,我没有时间,只是把主要想法。

解释:

  • 我使用列表切片“list[start:stop:step]”来仅获取要替换的单词。
  • 然后我使用 for 循环和 replace 方法将单词 ["automobile"、"manufacturer"、"children"] 替换为索引为 1、3 和 5 的标记列表。 [“汽车”、“制造商”、“孩子”]
tokens = input().split()
sentence = input()
c = 1
for word in tokens[::2]:
  sentence.replace(word, tokens[c]) 
  c += 2

print(sentence)
"The car maker recommends car seats for kids if the car doesn't already have one."

或者如果您想使用您的解决方案,只需调整打印缩进

word_pairs = {}

tokens = input().split()
sentence = input()

step = 2
for index in range(0,len(tokens), step):
    key = tokens[index]
    value = tokens[index+1]
    
    word_pairs[key] = value
    for original, new in word_pairs.items():
        sentence = sentence.replace(original, new)
        
 print(sentence)

【讨论】:

  • 请添加一两行来解释你在做什么。这将有助于读者更清楚地理解答案。
猜你喜欢
  • 2023-02-06
  • 2022-11-24
  • 2022-11-21
  • 2020-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
相关资源
最近更新 更多