首页 > 解决方案 > 如何遍历列表以计算字典中的键?

问题描述

我需要遍历一个被解析为一个名为语音的列表的语音,并计算每个标点符号的实例,并为字典中的值 +1。我在下面有一个标点符号列表和字典。

punclist = ['.', '!', '?']
puncdict = {'.':0,'!':0,'?':0}

标签: pythonlistdictionary

解决方案


不确定为什么演讲是一个列表,但您可以使用 acollection.Counter()来计算每个字符的出现次数,然后挑选出感兴趣的:

from collections import Counter

text = 'We will fight them on the beaches! Where are the apples? Oh, they are over there. etc. etc. etc.'

c = Counter(text)
punclist = ['.', '!', '?']
punctuation_counts = {k: c[k] for k in punclist}
print(punctuation_counts)
# {'.': 4, '!': 1, '?': 1}

如果你有一个单词列表,那么你会这样做:

c = Counter(''.join(word_list))

如果你想计算所有标点符号:

import string

punctuation_counts = {k: c[k] for k in string.punctuation}
print(punctuation_counts)
# {'!': 1, '"': 0, '#': 0, '$': 0, '%': 0, '&': 0, "'": 0, '(': 0, ')': 0, '*': 0, '+': 0, ',': 1, '-': 0, '.': 4, '/': 0, ':': 0, ';': 0, '<': 0, '=': 0, '>': 0, '?': 1, '@': 0, '[': 0, '\\': 0, ']': 0, '^': 0, '_': 0, '`': 0, '{': 0, '|': 0, '}': 0, '~': 0}

推荐阅读