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

2024-04-19 12:57:09 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用dict理解为字符串列表建立标点符号计数字典?我可以用这样一根弦来做:

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

Tags: infromtestimportchainforstringreturn
1条回答
网友
1楼 · 发布于 2024-04-19 12:57:09

为什么要数你自己?你知道吗

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})

相关问题 更多 >