我需要一些帮助。我有两个列表:

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可能是最简单(也是最短)的方法,但是字符串还附带了一个内置的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 comprehension
for sent in sentences:
  print sent, sum(sent.count(col) for col in color)

10-07 18:56