python - 如何更改此循环以插入单词“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
解决方案
只需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
推荐阅读
- c# - 协助使用 SQL 命令
- angular - NgxPermissions 不适用于延迟加载模块
- php - .htaccess 将所有页面重定向到移动版本
- java - OpenMPI:MPI.Init 挂在 Java 中 - 如何调试?
- android - com.android.inputmethod.latin 中的 ANR 原因:输入调度超时
- vmware-clarity - 如何使最左边的列适合垂直表格中的内容?
- php - 否则,如果语句在 php 中输出错误的变量?
- apache-spark - 为 Spark 应用程序设置 Cloudera 应用程序标签
- sql-server - 游标不添加数据,仅在单独执行时添加
- r - 如何正确地将数据导入 R 中的 h2o 客户端?