我創建了一個輸入,允許我制作一個句子串列(串列)和一個包含多個值的字典(dict)的輸入。串列和字典的元素根據用戶輸入的元素而有所不同
我嘗試通過從 {}
您有使用隨機、itertool 或 re 的解決方案嗎?我完全被封鎖了。
我的資料:
List = ["Je {suis|m'appelle} kevin rab et je suis {grand|petit} et {beau|moche}.", "Je {suis|m'appelle} sam slap et je suis {grand|petit} et {beau|moche}.", "Je {suis|m'appelle} bob clob et je suis {grand|petit} et {beau|moche}.", "Je {suis|m'appelle} lydie bal et je suis {grand|petit} et {beau|moche}."]
Dict = {"{suis|m'appelle}": ['suis', 'mpo%appelle'], '{grand|petit}': ['grand', 'petit'], '{beau|moche}': ['beau', 'moche']}
我正在尋找這樣的結果(隨機):
['Je mpo%appelle kevin rab et je suis grand et moche.', 'Je suis sam slap et je suis grand et beau.', 'Je mpo%appelle bob clob et je suis petit et moche.' , 'Je suis lydie bal et je suis grand et moche.']
uj5u.com熱心網友回復:
您不需要dict,您可以使用re.sub回呼函式來查找這些{...}區域并用其中一種替代方法替換它們:
>>> text = "Je {suis|m'appelle} kevin rab et je suis {grand|petit} et {beau|moche}."
>>> re.sub(r"\{(. ?)\}", lambda m: random.choice(m.group(1).split("|")), text)
'Je suis kevin rab et je suis petit et moche.'
>>> re.sub(r"\{(. ?)\}", lambda m: random.choice(m.group(1).split("|")), text)
"Je m'appelle kevin rab et je suis petit et beau."
檔案的相關摘錄:
If
repl是一個函式,它會在每個不重疊的pattern. 該函式采用單個匹配物件引數,并回傳替換字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476893.html
標籤:Python python-3.x 列表 字典
上一篇:將檔案中的字典存盤在嵌套字典中
下一篇:如何組合多個資料列并輸出為字典
