如果 Counter 对象的键的类型是str
, i.e.:
我可以这样做:
>>> vocab_counter = Counter("the lazy fox jumps over the brown dog".split())
>>> vocab_counter = Counter({k+u"\uE000":v for k,v in vocab_counter.items()})
>>> vocab_counter
Counter({'brown\ue000': 1,
'dog\ue000': 1,
'fox\ue000': 1,
'jumps\ue000': 1,
'lazy\ue000': 1,
'over\ue000': 1,
'the\ue000': 2})
将字符添加到所有键的快速和/或Python式的方法是什么?
上述方法是实现将字符附加到所有键上的最终计数器的唯一方法吗?还有其他方法可以实现相同的目标吗?
更好的方法是在创建计数器对象之前添加该字符。您可以使用生成器表达式来完成此操作Counter
:
In [15]: vocab_counter = Counter(w + u"\uE000" for w in "the lazy fox jumps over the brown dog".split())
In [16]: vocab_counter
Out[16]: Counter({'the\ue000': 2, 'fox\ue000': 1, 'dog\ue000': 1, 'jumps\ue000': 1, 'lazy\ue000': 1, 'over\ue000': 1, 'brown\ue000': 1})
如果在创建计数器之前无法修改单词,您可以覆盖Counter
对象以添加特殊字符在设置键的值时 https://docs.python.org/3.6/reference/datamodel.html#object.__setitem__.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)