我需要一些帮助。我有以下两个列表:
sentences = ['The green monkey green age the blue egg','How many yellow green monkey"s are in the green forest']
color =['orange', 'green', 'yellow', 'violet', 'blue']
totals = []
for sent in sentences:
print sent
for sent in sentences:
totals.add((sent, sum(sent.count(col) for col in color))
我的目标是计算颜色元素出现在句子中任何给定元素中的次数。因此,我的输出将包含每个句子元素和存在的彩色元素的计数。任何帮助,将不胜感激。我是一个初学者,到目前为止喜欢python :)
使用Counter
可能是最Python的(也是最短的)方法,但是字符串还带有一个内置count
方法,可以使用:
color =['orange', 'green', 'yellow', 'violet', 'blue']
sentences = ['The green monkey age the blue egg', 'How many yellow monkey"s are in the green forest']
for sent in sentences:
print sent
for col in color:
print "", col, sent.count(col)
输出:
The green monkey age the blue egg
orange 0
green 1
yellow 0
violet 0
blue 1
How many yellow monkey"s are in the green forest
orange 0
green 1
yellow 1
violet 0
blue 0
如果您只想让句子位于句子中颜色总数的旁边,则将最后一个for
循环替换为sum和list理解:
for sent in sentences:
print sent, sum(sent.count(col) for col in color)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句