繁体   English   中英

Python 单词替换列表开启关键字

[英]Python word replacement list switch on key word

有谁知道如何修改这个脚本,以便它为单词“rat”的每个实例切换字典

word_replacement = [{'dog': 'Bob', 'cat': 'Sally', 'bird': 'John', 'rat': 'Pat'},
        {'dog': 'Brown', 'cat': 'White', 'bird': 'Black', 'rat': 'Grey'},
        {'dog': 'Bark', 'cat': 'Meow', 'bird': 'Chirp', 'rat': 'Squeek'}]

with open("main.txt") as main:
    words = main.read().split()
 
replaced = []
for y in words:
    replacement = word_replacement.get(y, y)
    replaced.append(replacement)
text = ' '.join(replaced)

 
print (text)

new_main = open("main.txt", 'w')
new_main.write(text)
new_main.close()

样本输入:

dog bird rat dog cat cat rat bird rat cat dog

所需的 output:

Bob John Pat Brown White White Grey Chirp Squeek Sally Bob

已经指出word_replacement是一个列表,因此您必须使用索引访问其元素,当遇到rat时您将递增:

word_replacement = [{'dog': 'Bob', 'cat': 'Sally', 'bird': 'John', 'rat': 'Pat'},
        {'dog': 'Brown', 'cat': 'White', 'bird': 'Black', 'rat': 'Grey'},
        {'dog': 'Bark', 'cat': 'Meow', 'bird': 'Chirp', 'rat': 'Squeek'}]

input_str = "dog bird rat dog cat cat rat bird rat cat dog"
words = input_str.split()

replaced = []
dic_list_idx = 0
list_len = len(word_replacement)
for w in words:
    replacement = word_replacement[dic_list_idx % list_len].get(w, w)
    replaced.append(replacement)
    if w == "rat":
        dic_list_idx += 1
text = ' '.join(replaced)


print (text)

new_main = open("main.txt", 'w')
new_main.write(text)
new_main.close()

dic_list_idx % list_len允许您在到达列表末尾时从第一个字典开始。

Output:

Bob John Pat Brown White White Grey Chirp Squeek Sally Bob

注意:在您的示例中,键和值之间似乎有些混淆(不应该用John替换bird吗?)

有多种方法,但首先想到的是 2:

  1. 在循环中有一个计数器,当你得到“老鼠”时你会增加它,如果你到达终点则重置为零:
i = 0
for y in words.split():
    replacement = word_replacement[i][y]
    replaced.append(replacement)
    if y == 'rat':
        i += 1
    if i == len(word_replacement):
        i = 0
text = ' '.join(replaced)

print(text)
  1. 始终使用列表中的第一个字典,但在每次出现单词“rat”时弹出第一个字典并将其推到后面:D
for y in words.split():
    replacement = word_replacement[0][y]
    replaced.append(replacement)
    if y == 'rat':
        word_replacement.append(word_replacement.pop(0))
text = ' '.join(replaced)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM