有沒有人知道如何修改此腳本,以便每次找到特定單詞時都遍歷鍵值
word_replacement = {'rat':['pat', 'grey', 'squeeky']}
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()
樣本輸入:
rat went to the rat park to play with rat friends at the rat party
所需的輸出:
pat went to the grey park to play with squeeky friends at the pat party
uj5u.com熱心網友回復:
當您獲得給定單詞的字典條目時,您需要將其值作為串列進行處理,并選擇該串列中的一項作為原始單詞的替代品(而不是附加整個串列)。每次使用串列中的專案時,都應將其移到末尾,以便下一次出現的關鍵字使用不同的替換詞:
word_replacement = {'rat':['pat', 'grey', 'squeeky']}
words = "rat went to the rat park to play with rat friends at the rat party".split()
replaced = []
for y in words:
replacements = word_replacement.get(y) # get replacement list
if replacements: # if there is one, change y
y = replacements.pop(0) # use first replacement word
replacements.append(y) # and move it to the end of the list
replaced.append(y) # add original or replaced word
text = ' '.join(replaced)
print (text)
pat went to the grey park to play with squeeky friends at the pat party
uj5u.com熱心網友回復:
replace_idx = 0
for i, y in enumerate(words):
if y in word_replacement:
words[i] = word_replacement[y][replace_idx]
replace_idx = (replace_idx 1)%3
text = ' '.join(words)
print(text)
這將替換單詞而不創建新的單詞串列。此外,它適用于更大的 word_replacements 字典。
uj5u.com熱心網友回復:
最簡單的方法是擁有一個計數器并在您更換它時增加它。我不知道您的實際word_replacementdict 的那種形式,但您可能想要保存多個計數器,每個計數器都用于跟蹤不同的單詞。
word_replacement = {'rat':['pat', 'grey', 'squeeky']}
with open("main.txt") as main:
words = main.read().split()
replaced = []
counter_for_rat = 0 # This is your counter
for y in words:
n = word_replacement.get(y) # Return None if word not in word_replacement
if n is not None:
n = n[counter_for_rat % len(n)] # This prevents index out of range
counter_for_rat = 1
else:
n = y
replaced.append(n)
text = ' '.join(replaced)
print (text)
new_main = open("main.txt", 'w')
new_main.write(text)
new_main.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358750.html
上一篇:將IEnumerable<Ienumerable<T>>轉換為Dictionary<key,IEnumerable<T>>
下一篇:洗掉字典鍵,如果值為空
