gpt4 book ai didi

python - 将字典列表中的值映射到 Python 中的字符串

转载 作者:行者123 更新时间:2023-12-05 03:33:26 25 4
gpt4 key购买 nike

我正在研究这样的句子结构:

sentence = "PERSON is ADJECTIVE"
dictionary = {"PERSON": ["Alice", "Bob", "Carol"], "ADJECTIVE": ["cute", "intelligent"]}

我现在需要所有可能的组合来从字典中形成这个句子,例如:

Alice is cute
Alice is intelligent
Bob is cute
Bob is intelligent
Carol is cute
Carol is intelligent

上面的用例比较简单,用下面的代码完成

dictionary = {"PERSON": ["Alice", "Bob", "Carol"], "ADJECTIVE": ["cute", "intelligent"]}

for i in dictionary["PERSON"]:
for j in dictionary["ADJECTIVE"]:
print(f"{i} is {j}")

但我们是否也可以针对更长的句子进行扩展?

例子:

sentence = "PERSON is ADJECTIVE and is from COUNTRY" 
dictionary = {"PERSON": ["Alice", "Bob", "Carol"], "ADJECTIVE": ["cute", "intelligent"], "COUNTRY": ["USA", "Japan", "China", "India"]}

这应该再次提供所有可能的组合,例如:

Alice is cute and is from USA
Alice is intelligent and is from USA
.
.
.
.
Carol is intelligent and is from India

我尝试使用 https://www.pythonpool.com/python-permutations/ , 但是句子都是混在一起的——但是我们怎么才能固定几个单词呢,比如这个例子中的单词 "and is from" 是固定的

本质上,如果字典中的任何键等于字符串中的单词,则该单词应替换为字典中的值列表。

任何想法都会很有帮助。

最佳答案

我的答案基于两个构建 block itertools.productzip

itertools.product 将允许我们获取字典列表值的各种组合

zip 使用原始键和上面的组合将允许我们创建一个元组列表,我们可以使用 replace

import itertools

sentence = "PERSON is ADJECTIVE and is from COUNTRY"
dictionary = {"PERSON": ["Alice", "Bob", "Carol"], "ADJECTIVE": ["cute", "intelligent"], "COUNTRY": ["USA", "Japan", "China", "India"]}

keys = dictionary.keys()
for values in itertools.product(*dictionary.values()):
new_sentence = sentence
for tpl in zip(keys, values):
new_sentence = new_sentence.replace(*tpl)
print(new_sentence)

如果您恰好有能力控制“句子”模板,您可以:

sentence = "{PERSON} is {ADJECTIVE} and is from {COUNTRY}"

那么你可以将其简化为:

sentence = "{PERSON} is {ADJECTIVE} and is from {COUNTRY}"
dictionary = {"PERSON": ["Alice", "Bob", "Carol"], "ADJECTIVE": ["cute", "intelligent"], "COUNTRY": ["USA", "Japan", "China", "India"]}

keys = dictionary.keys()
for values in itertools.product(*dictionary.values()):
new_sentence = sentence.format(**dict(zip(keys, values)))
print(new_sentence)

两者都应该给你这样的结果:

Alice is cute and is from USA
Alice is cute and is from Japan
...
Carol is intelligent and is from China
Carol is intelligent and is from India

请注意,模板中的出现顺序并不重要,两种解决方案都应适用于以下模板:

sentence = "PERSON is from COUNTRY and is ADJECTIVE"

或者情况2

sentence = "{PERSON} is from {COUNTRY} and is {ADJECTIVE}"

跟进:

如果字典中有可能包含句子模板中没有的项目,会发生什么情况?目前,这并不理想,因为使用 product() 生成句子的方式假设所有键都是,而我们目前会生成重复项。

最简单的解决方法是确保字典只包含感兴趣的键...

在第一种情况下,这可能会那样做。

dictionary = {key: value for key, value in dictionary.items() if key in sentence}

或者在第二种情况下:

dictionary = {key: value for key, value in dictionary.items() if f"{{{key}}}" in sentence}

关于python - 将字典列表中的值映射到 Python 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70325758/

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