我需要运行一个语音,该语音被解析为一个名为语音的列表,并对标点符号的每个实例进行计数,并为字典中的值 +1。我在下面有一个标点符号列表和字典。
punclist = ['.', '!', '?']
puncdict = {'.':0,'!':0,'?':0}
答案 0 :(得分:1)
不确定为什么演讲是一个列表,但您可以使用 collection.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}