Skip to main content
 首页 » 编程设计

python之字符串列表的标点符号字典

2024年09月07日41bjzhanghao

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

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