![](/img/trans.png)
[英]Cant replace all the word with replacement in python based on the match in dictionary list
[英]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:
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)
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.