繁体   English   中英

使用数组的字典的Python字符串格式

[英]Python string format using dict of arrays

我有一个值的词库(词典):

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或者我需要编写自己的自定义格式功能(包括单词/关键字匹配)?

我相信您可以通过继承内置的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

UPDATE

为了确保我的答案与您的问题/要求完全匹配,我对上面的代码进行了调整以包括短语数组。 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

这种方法怎么样:

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'
>>> 

希望可以为您服务。

本身并不需要自定义format功能。 format只需要取值(以及可选的各种格式说明)。

我建议您定义一个函数,该函数接受源词并根据您想要的启发式方法返回同义词(可能是列表的随机元素),然后在format调用内调用该函数。

即像

'the water is {0}'.format(getSynonym('cold'))

根据OP的评论进行编辑:

如果您有动态键,则可以将代表键的变量直接传递到函数中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM