如果我了解您的问题,collections.Counter()可以解决此问题。
文档中的示例似乎可以解决您的问题。
# Tally occurrences of words in a listcnt = Counter()for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: cnt[word] += 1print cnt# Find the ten most common words in Hamletimport rewords = re.findall('w+', open('hamlet.txt').read().lower())Counter(words).most_common(10)从上面的示例中,您应该能够:
import reimport collectionswords = re.findall('w+', open('1976.03.txt').read().lower())print collections.Counter(words)EDIT 幼稚的方法来显示一种方式。
wanted = "fish chips steak"cnt = Counter()words = re.findall('w+', open('1976.03.txt').read().lower())for word in words: if word in wanted: cnt[word] += 1print cnt


