使用数组字典的Python字符串格式化
我有一个值的同义词典:
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
,还是说我需要自己写一个自定义的格式化功能,包括单词和关键词的匹配?
3 个回答
0
其实你并不需要什么特别的 format
功能。format
只是用来接收一些值(还有可选的格式设置)。
我建议你定义一个函数,这个函数接收一个单词,然后根据你想要的规则返回一个同义词(比如从列表中随机选一个),然后在调用 format
的时候使用这个函数。
也就是说,可以像这样做:
'the water is {0}'.format(getSynonym('cold'))
根据提问者的评论进行编辑:
如果你有动态的键值,可以直接把代表这个键的变量传递给你的函数。
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'
>>>
希望能对你有所帮助。
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__
方法可以让你对每个键值对的值(一个列表)做出假设,这样你就可以从这个值的列表中随机返回一个项目。
上面代码的输出结果如下:
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