python - 字符串列表的标点符号计数字典

标签 python string punctuation dictionary-comprehension

如何使用字典理解为字符串列表构建标点符号计数字典?我能够对单个字符串执行此操作,如下所示:

import string

test_string = "1990; and 1989', \ '1975/97', '618-907 CE"
counts = {p:test_string.count(p) for p in string.punctuation}

编辑:对于将来可能需要此操作的任何人,以下是从下面复制的 Patrick Artner 的答案,并进行了很小的修改以仅保留标点符号计数:

# return punctuation Counter dict for string/list/pd.Series

import string
from collections import Counter
from itertools import chain

def count_punctuation(str_series_or_list):
    c = Counter(chain(*str_series_or_list))
    unwanted = set(c) - set(string.punctuation)
    for unwanted_key in unwanted: del c[unwanted_key]
    return c

最佳答案

为什么要数自己?

import string
from collections import Counter


test_string = "1990; and 1989', \ '1975/97', '618-907 CE"

c = Counter(test_string)  # counts all occurences

for p in string.punctuation:   # prints the one in string.punctuation
    print(p , c[p])            # access like dictionary (its a subclass of dict)
print(c)

输出:

! 0
" 0
# 0
$ 0
% 0
& 0
' 4
( 0
) 0
* 0
+ 0
, 2
- 1
. 0
/ 1
: 0
; 1
< 0
= 0
> 0
? 0
@ 0
[ 0
\ 1
] 0
^ 0
_ 0
` 0
{ 0
| 0
} 0
~ 0
Counter({'9': 7, ' ': 6, '1': 4, "'": 4, '7': 3, '0': 2, '8': 2, ',': 2, ';': 1, 'a': 1, 'n': 1, 'd': 1, '\\': 1, '5': 1, '/': 1, '6': 1, '-': 1, 'C': 1, 'E': 1})

计数器类似于字典:参见 https://docs.python.org/2/library/collections.html#collections.Counter

编辑:列表中的多个字符串:

import string
from collections import Counter
from itertools import chain

test_strings = [ "1990; and 1989', \ '1975/97', '618-907 CE" , "someone... or no one? that's the question!", "No I am not!"]

c = Counter(chain(*test_strings))

for p in string.punctuation:
    print(p , c[p])

print(c)

输出:(删除 0 个条目)

! 2
' 5
, 2
- 1
. 3
/ 1
; 1
? 1
\ 1
Counter({' ': 15, 'o': 8, '9': 7, 'n': 6, "'": 5, 'e': 5, 't': 5, '1': 4, 'a': 3, '7': 3, 's': 3, '.': 3, '0': 2, '8': 2, ',': 2, 'm': 2, 'h': 2, '!': 2, ';': 1, 'd': 1, '\\': 1, '5': 1, '/': 1, '6': 1, '-': 1, 'C': 1, 'E': 1, 'r': 1, '?': 1, 'q': 1, 'u': 1, 'i': 1, 'N': 1, 'I': 1})

关于python - 字符串列表的标点符号计数字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48480352/

相关文章:

python - Python NameNode脚本

python - 仅使用 python 正则表达式从最新的字符串中获取

javascript - 如何在Javascript中将问号包围的文本提取到数组中

Java-将 BigDecimal 作为字符串返回 : Returns int

python - 如何在 Python 中打印后在两个变量之间添加空格

python - 让 pytest 等待用户输入

php - 我忍不住想到我做错了(又是 Python)

python - 用 super() 装饰子类的 __init__ 方法

python - 从 unicode 字符串中删除选定的标点符号

java - 如何忽略 java 中的标点符号和空格?