python - 如何遍历列表以计算字典中的键?
问题描述
我需要遍历一个被解析为一个名为语音的列表的语音,并计算每个标点符号的实例,并为字典中的值 +1。我在下面有一个标点符号列表和字典。
punclist = ['.', '!', '?']
puncdict = {'.':0,'!':0,'?':0}
解决方案
不确定为什么演讲是一个列表,但您可以使用 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}
推荐阅读
- angular - Angular 9 窗口滚动在 Internet Explorer 中不起作用
- python - 使用 PyInstaller 编译 python 会引发许多警告
- android - 无法从 `src\pages\home\index.js` 解析模块 `../images/icon.png`:
- typescript - 强制两个函数在 TypeScript 中采用相同的参数类型
- python - Pytorch 抛出越界错误?期望一个标量
- dockerfile - SageMaker ANSI 转义码
- javascript - 循环遍历 mongodb 文档 id 数组并查询该 id 并将结果存储在新数组中给出空数组
- r - ggplot2 用于交互图 APA 风格
- r - R:有没有办法 cbind 非数字列
- firebase - 颤抖的问题:为什么这会给我一堆或错误?下面是我的代码和错误