gpt4 book ai didi

python - 用多个字典值替换字符串中的单词?

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:42 25 4
gpt4 key购买 nike

我有一个句子模板字符串和一个包含所需替换词的字典:

template = "Who was <Name>'s <Job> in <Month>?"
dictionary = {Name: [John,Peter,Paul],
Job: [Designer,Carpenter,Lawyer],
Month:[October,July,March]
}

我想生成一个句子列表,每个替换组合一个:

question_list=["Who was <John>'s <Lawyer> in <October>?",
"Who was <Peter>'s <Lawyer> in <October>?",
"Who was <John>'s <Designer> in <July>?",
... ]

列表的顺序无关紧要,我不需要删除括号“< >”。

目前我有:

def replace(template, dictionary):
question_list = []
for word in template:
for key in dictionary:
if word == key:
new_string = template.replace(word, dictionary[key])
question_list.append(new_string)
return question_list

这会将 question_list 作为空列表返回。

我很确定我的主要问题是我不知道如何/没有第三个 for 循环 来访问字典值列表中的每个项目,但我没有足够的经验知道我搞砸了有多严重。我该如何解决这个问题?

最佳答案

您可以使用 re.subitertools.product:

import re, itertools
template = "Who was <Name>'s <Job> in <Month>?"
dictionary = {'Name': ['John', 'Peter', 'Paul'], 'Job': ['Designer', 'Carpenter', 'Lawyer'], 'Month': ['October', 'July', 'March']}
headers = re.findall('(?<=\<)\w+(?=\>)', template)
full_vals = itertools.product(*[dictionary[i] for i in headers])
final_results = [re.sub('\<\w+\>', lambda x:'{'+x.group()[1:-1]+'}', template).format(**dict(zip(headers, i))) for i in full_vals]

输出:

["Who was John's Designer in October?", "Who was John's Designer in July?", "Who was John's Designer in March?", "Who was John's Carpenter in October?", "Who was John's Carpenter in July?", "Who was John's Carpenter in March?", "Who was John's Lawyer in October?", "Who was John's Lawyer in July?", "Who was John's Lawyer in March?", "Who was Peter's Designer in October?", "Who was Peter's Designer in July?", "Who was Peter's Designer in March?", "Who was Peter's Carpenter in October?", "Who was Peter's Carpenter in July?", "Who was Peter's Carpenter in March?", "Who was Peter's Lawyer in October?", "Who was Peter's Lawyer in July?", "Who was Peter's Lawyer in March?", "Who was Paul's Designer in October?", "Who was Paul's Designer in July?", "Who was Paul's Designer in March?", "Who was Paul's Carpenter in October?", "Who was Paul's Carpenter in July?", "Who was Paul's Carpenter in March?", "Who was Paul's Lawyer in October?", "Who was Paul's Lawyer in July?", "Who was Paul's Lawyer in March?"]

关于python - 用多个字典值替换字符串中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51974207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com