我仍在學習python,嘗試一些東西。從列表中匹配
我有代碼在文本中搜索單詞'Lorem'並用列表中的隨機單詞替換。這是行得通的。
我現在要做的是如何檢查列表中的單詞(單詞= ['和','a','是',''])是否在文本中,並用另一個單詞中的另一個單詞替換(t = ['TEXT','REPLACE','WORD'])。
我想用變量或循環直通列表替換'Lorem'或用單詞打開txt文件來檢查。
解析度=應用re.sub( '的Lorem',拉姆達X:random.choice(T),文本)
如果可能的話,如果有人可以告訴我所有的3個選項:
-loop通過列表 - 變量 - 用文字打開內部文件
或者也許還有其他更好的方法?
謝謝!
這裏是完整的代碼
import re
import random
t = ['TEXT', 'REPLACE', 'WORD']
text = '''Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum'''
words = ['and', 'a', 'is', 'the']
res = re.sub('Lorem', lambda x: random.choice(t), text)
print(res)
如何'words'對應't'?我們是否假設你只是隨機地用't'中的一個單詞替換?如果沒有,我建議你創建一個字典映射哪些單詞應該被某些其他單詞替換。 – blacksite