内容旋转 - Python

Content spinning - Python

我创建了一个允许我制作句子列表 (list) 的输入和一个包含具有多个值的字典 (dict) 的输入。 列表和字典的元素根据用户输入的元素不同

我试图通过从 {}

之间的数据中随机选取,让脚本从 List 中生成句子列表

您有使用 random、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', 'm%1apo%appelle'], '{grand|petit}': ['grand', 'petit'], '{beau|moche}': ['beau', 'moche']}

我正在搜索这样的结果(随机):

['Je m%1apo%appelle kevin rab et je suis grand et moche.', 'Je suis sam slap et je suis grand et beau.', 'Je m%1apo%appelle bob clob et je suis petit et moche.', 'Je suis lydie bal et je suis grand et moche.']

您不需要 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 is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.