有誰知道如何修改這個腳本,以便它為單詞“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
所需的輸出:
Bob John Pat Brown White White Grey Chirp Squeek Sally Bob
uj5u.com熱心網友回復:
已經指出這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 允許您在到達串列末尾時從第一個字典開始。
輸出:
Bob John Pat Brown White White Grey Chirp Squeek Sally Bob
注意:在您的示例中,鍵和值之間似乎有些混淆(不應bird替換為John?)
uj5u.com熱心網友回復:
有多種方法,但首先想到的是兩種:
- 在回圈中設定一個計數器,每當您獲得 'rat' 時,該計數器就會增加,如果到達終點,則重置為零:
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)
- 始終使用串列中的第一個字典,但是每次出現“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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358753.html
上一篇:將python字典鍵乘以一個常量
下一篇:計算字典的每個值中術語的出現次數
