我正在使用字典替換字串。
用字典代替很容易,但是當用同一個詞替換所有詞時,句子就變得尷尬了。
因此,我嘗試一次讀取一行并替換一次,但失敗了。
# A function that randomly replaces a word
def ttc(*arg):
a = random.choice([*arg])
return ''.join(a)
text = """
I'm working on replacing a string using a dictionary.
I'm working on replacing a string using a dictionary.
I'm working on replacing a string using a dictionary.
I'm working on replacing a string using a dictionary.
I'm working on replacing a string using a dictionary.
I'm working on replacing a string using a dictionary.
"""
a_dic = {'working': ttc('tttttt', 'yyyyy', 'iiiiii'),
'using': ttc('qqqq', 'eeeee', 'rrrrrr'),
'on': ttc('cdcd', 'vvvdvdvv', 'dvd')
}
new_list = []
pos = -1
for s in text.split("\n"):
pos = 1
if s == "":
new_list.append(s)
else:
for key in a_dic.keys():
s = s.replace(key, a_dic[key])
if pos == len(a_dic) - 1:
new_list.append(s)
for d in new_list:
print(d)
使用字典執行隨機字串替換時,您可以用不同的單詞替換幾個相同的單詞嗎?我想要的結果如下
text = """
I'm tttttt dvd replacing a string eeeee a dictionary.
I'm yyyyy cdcd replacing a string qqqq a dictionary.
I'm tttttt cdcd replacing a string qqqq a dictionary.
I'm tttttt vvvdvdvv replacing a string eeeee a dictionary.
I'm iiiiii cdcd replacing a string rrrrrr a dictionary.
I'm iiiiii vvvdvdvv replacing a string qqqq a dictionary.
"""
幫助
uj5u.com熱心網友回復:
我不確定你為什么需要這個ttc函式,因為你choice已經在你的串列中選擇了一個元素(字串)。所以你不需要加入結果。
您可以將字典值設定為函式并將它們用作替換re.sub:
import re
a_dic = {'working': lambda x: random.choice(['tttttt', 'yyyyy', 'iiiiii']),
'using': lambda x: random.choice(['qqqq', 'eeeee', 'rrrrrr']),
'on': lambda x: random.choice(['cdcd', 'vvvdvdvv', 'dvd'])
}
changed_text = text
for k in a_dic:
changed_text = re.sub(rf'(?<=\W){k}(?=\W)', a_dic[k], changed_text)
print(changed_text)
輸出:
I'm tttttt dvd replacing a string eeeee a dictionary.
I'm yyyyy cdcd replacing a string qqqq a dictionary.
I'm yyyyy cdcd replacing a string qqqq a dictionary.
I'm tttttt vvvdvdvv replacing a string eeeee a dictionary. cdcd
I'm yyyyy dvd replacing a string eeeee a dictionary.
I'm tttttt vvvdvdvv replacing a string qqqq a dictionary.
編輯:
您還可以創建一個“元”函式來避免遍歷字典:
def replace_fun(match_obj):
word = match_obj.group(0)
if word in a_dic:
return a_dic[word](word)
else:
return word
changed_text = re.sub(r'\w ', replace_fun, text)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/489294.html
標籤:python-3.x 代替
上一篇:計算數字的位數總和時出現負數錯誤
