有誰知道如何修改這個腳本,以便它在找到單詞時隨機更改單詞。
即并非“熊”的每個實體都變成“蛇”
# A program to read a file and replace words
word_replacement = {'Bear':'Snake', 'John':'Karen', 'Bird':'Owl'}
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()
uj5u.com熱心網友回復:
一種方法是隨機決定應用替換:
import random
replacement = word_replacement.get(y, y) if random.random() > 0.5 else y
在上面的示例中,它將以~0.5 的概率更改"Bear"為"Snake"(或 word_replacement 中的任何其他單詞)。您可以將值更改為您想要的隨機性。
放在一起:
# A program to read a file and replace words
import random
word_replacement = {'Bear': 'Snake', 'John': 'Karen', 'Bird': 'Owl'}
with open("main.txt") as main:
words = main.read().split()
replaced = []
for y in words:
replacement = word_replacement.get(y, y) if random.random() > 0.5 else y
replaced.append(replacement)
text = ' '.join(replaced)
print(text)
with open("main.txt", 'w') as outfile:
outfile.write(text)
輸出 (Bear Bear Bear as main.txt)
Snake Bear Bear
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/341242.html
下一篇:將檔案發送到Java中的API
