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

标签 python list dictionary replace string-matching

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

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/

相关文章:

python - PyAudio IOError : No Default Input Device Available

java - 空指针异常修复 - 列表

c# - 如何减少执行时间?

python - 在 Python 上模拟鼠标点击

python - 来自 python 的 FQL 多重查询因 unicode 查询而失败

python - 迭代Python列表: order of iteration

c# - 字典、哈希集的访问时间

swift - 可以将此 Alamofire 结果转换为字典数组

dictionary - 在 OCaml 中使用 Map.update

python - 无法包装 QWebView.load 方法