我有一个值词库(词典):
words = dict(
'hot' = ['hot', 'scalding', 'warm'],
'cold' = ['cold', 'frigid', 'freezing'],
...)
我想使用这个同义词库循环一个字符串列表,用来自同义词库的随机条目格式化标签。我不会提前知道关键词是什么。
phrases = ['the water is {word.cold}', 'the sun is {word.hot}', ...]
formatted = [phrase.format(word=words, somerandomizingfunction) for phrase in phrases]
但是这(正如预期的那样)是将整个数组插入到字符串中。有没有办法将choice
函数传递给format
,还是我需要编写自己的自定义格式功能,包括单词/键匹配?
答案 0 :(得分:3)
我相信你可以通过继承内置dict
类来实现你想要的。请参阅 http://dbgr.cc/k
import random
class WordDict(dict):
def __getitem__(self, key):
vals = dict.__getitem__(self, key)
return random.choice(vals)
words = WordDict(
cold = ["cold", "frigid", "freezing"],
hot = ["scathing", "burning", "hot"]
)
for x in xrange(10):
print('the water is {word[cold]}'.format(word=words))
覆盖__getitem__
方法将允许您假设每个键/值对的每个值(列表),此时您可以从值列表中返回随机项。< / p>
以上代码的输出如下:
the water is freezing
the water is cold
the water is freezing
the water is frigid
the water is cold
the water is frigid
the water is cold
the water is freezing
the water is freezing
the water is freezing
<强>更新强>
为了确保我的答案完全符合您的问题/请求,我已经调整了上面的代码以包含短语数组。在 http://dbgr.cc/n
上进行演示/调试/可调整import random
class WordDict(dict):
def __getitem__(self, key):
vals = dict.__getitem__(self, key)
return random.choice(vals)
words = WordDict(
cold = ["cold", "frigid", "freezing"],
hot = ["scathing", "burning", "hot"]
)
phrases = ['the water is {word[cold]}', 'the sun is {word[hot]}']
for x in xrange(10):
for phrase in phrases:
print phrase.format(word=words)
输出:
the water is frigid
the sun is scathing
the water is freezing
the sun is burning
the water is freezing
the sun is hot
the water is cold
the sun is scathing
the water is freezing
the sun is hot
the water is cold
the sun is scathing
the water is frigid
the sun is scathing
the water is frigid
the sun is hot
the water is frigid
the sun is scathing
the water is freezing
the sun is hot
答案 1 :(得分:1)
这种方法怎么样:
import random
words = dict(hot=['hot', 'scalding', 'warm'],
cold=['cold', 'frigid', 'freezing'])
演示:
>>>
>>> 'the water is {}'.format(random.choice(words['cold']))
'the water is frigid'
>>> 'the water is {}'.format(random.choice(words['cold']))
'the water is freezing'
>>> 'the water is {}'.format(random.choice(words['cold']))
'the water is frigid'
>>> 'the water is {}'.format(random.choice(words['cold']))
'the water is cold'
>>>
希望可以帮到你。
答案 2 :(得分:0)
本身并不需要自定义format
功能。 format
只需要取值(以及可选的各种格式规范)。
我建议你定义一个函数,它接受源词并根据你想要的启发式(也许是列表的随机元素)返回同义词,然后在调用{{1}内部调用该函数相反。
即。
之类的东西format
根据OP的评论进行编辑:
如果你有动态键,你可以将代表键的变量直接传递给你的函数。