【问题标题】:Generate variant strings based on replacement dictionary for some words only in Python仅在 Python 中根据替换字典为某些单词生成变体字符串
【发布时间】:2017-07-09 15:18:06
【问题描述】:

给定一个字符串和一个单词替换字典,我试图让 python 返回所有变体字符串。例如。对于字符串“One go to market”和替换字典 {'One': ['One','Two','Three'], 'market': ['town','bed']} 我想返回:['一个去镇上','两个去镇上','三个去镇上',一个去睡觉','两个去睡觉','三个去睡觉']。目前我只有在有两个替换选项时才能使用它。

我的部分工作方法使用从字典生成的单词列表,例如在上面的例子中,我有 ['One,Two,Three','went','to','town,bed']。这个这个:

def perm(wordlist):
    a=[[]]
    for i in wordlist:
        if ',' in i:
            wds=i.split(',')
            for alis in a:
                alis.append(wds[0])
            for j in wds[1:]:
                b=[x[:-1] for x in a]
                for alis in b:
                    alis.append(j)
                    a=a+b
        else:
            for alis in a:
                alis.append(i)
    return a

对于 ['One,Two','went','to','town,bed'] 我得到了所需的结果,但任何时候有两个以上的选项都是混乱的。

【问题讨论】:

  • 到目前为止您尝试过什么?你能发布你的代码吗?
  • 另外,您想如何处理重复项? “再去一次酒店”如何处理?在这种情况下,您希望生成 3 个句子还是 9 个句子?
  • 在这种情况下有 9 个句子(尽管根据我的输入可能不会出现这种情况。)
  • 代码现在已粘贴 - 抱歉,格式化需要一些时间 - 我是新人

标签: python string dictionary


【解决方案1】:

假设你有这些:

string = "One went to market"
dict_repl = {'One':['One','Two','Three'],'market':['town','bed']}

您可以使用string comprehensionstr.replace 使用这一个衬垫获得预期的结果:

result = [string.replace('market',v).replace('One',i) for v in dict_repl['market'] for i in dict_repl['One']]

输出:

['One went to town', 'Two went to town', 'Three went to town', 'One went to bed', 'Two went to bed', 'Three went to bed']

我相信这就是您的要求。

【讨论】:

  • 谢谢,这是所需的输出,但是您如何使用包含几十个键和几百个值的字典使其适应数千种不同的输入?
  • 你仍然希望 One、Two 和 Three 迭代你不同的其他词,例如“One go to market with Annie”、“One go to market with Mikasa”,然后是“two”,然后是“”三” ?我真的没有得到你正在寻找的组合@Smallpip
  • 是的:一个与 mikasa,两个与 mikasa,三个与 mikasa,一个与 annie,两个与 annie,等等。所以所有在 repl_dict 中包含条目的单词都会生成一个新字符串,其中所有其他单词都在repl_dict,并且没有条目的单词对所有字符串都是通用的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多