【发布时间】:2023-03-26 00:30:01
【问题描述】:
我正在研究这样的句子结构:
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" 是固定的
基本上,如果字典中的任何键与字符串中的单词相等,则该单词应替换为字典中的值列表。
任何想法都会很有帮助。
【问题讨论】:
-
如果您需要入门帮助,我会看看
itertools.product(*dictionary.values())为您提供什么, -
你可能想把你的句子转换成
str.format()知道如何处理的东西,这样你就不必自己做replace的东西了。
标签: python python-3.x list python-2.7 nlp