首页 > 解决方案 > 如何更改此循环以插入单词“CHANGE”

问题描述

这是我正在使用的代码:

words_input = "Duck Bear Bear Duck Duck Bear Bear Bear Bear Duck Bear Bear Duck Duck"

replacements = [{'Bear': ["Black", "Woods"], 'Duck': ["Bird", "Feathers"]},
                {'Bear': ["Grizzly", "Woods"], 'Duck': ["Quack", "Feathers"]},
                {'Bear': ["Grizzly", "Black"], 'Duck': ["Quack", "Bird"]}]

output = []
index_replace = 0
count_replace = {key: 0 for key in replacements[0].keys()}
for word in words_input.split():
    if count_replace[word] == len(replacements[index_replace][word]):
        # We need to cycle through the replacements
        index_replace = (index_replace + 1) % len(replacements)
        count_replace = {key: 0 for key in replacements[0].keys()}
    idx_word = count_replace[word]
    output.append(replacements[index_replace][word][idx_word])
    count_replace[word] += 1

output_words = ' '.join(output)
print(output_words)
# Bird Black Woods Feathers Quack Grizzly Woods Grizzly Black Quack Black Woods Bird Feathers

我希望CHANGE每次字典列表更改时都插入单词“”,以便输出看起来像

Bird Black Woods Feathers CHANGE Quack Grizzly Woods CHANGE Grizzly Black Quack CHANGE Black Woods Bird Feathers

代替

Bird Black Woods Feathers Quack Grizzly Woods Grizzly Black Quack Black Woods Bird Feathers

标签: pythondictionaryreplace

解决方案


只需output.append("CHANGE")在...列表更改时添加?

words_input = "Duck Bear Bear Duck Duck Bear Bear Bear Bear Duck Bear Bear Duck Duck"

replacements = [{'Bear': ["Black", "Woods"], 'Duck': ["Bird", "Feathers"]},
                {'Bear': ["Grizzly", "Woods"], 'Duck': ["Quack", "Feathers"]},
                {'Bear': ["Grizzly", "Black"], 'Duck': ["Quack", "Bird"]}]

output = []
index_replace = 0
count_replace = {key: 0 for key in replacements[0].keys()}
for word in words_input.split():
    if count_replace[word] == len(replacements[index_replace][word]):
        output.append("CHANGE") # << here is the change
        # We need to cycle through the replacements
        index_replace = (index_replace + 1) % len(replacements)
        count_replace = {key: 0 for key in replacements[0].keys()}
    idx_word = count_replace[word]
    output.append(replacements[index_replace][word][idx_word])
    count_replace[word] += 1

output_words = ' '.join(output)
print(output_words)
#Bird Black Woods Feathers CHANGE Quack Grizzly Woods CHANGE Grizzly Black Quack CHANGE Black Woods Bird Feathers

推荐阅读