如何使用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
为什么要数你自己?你知道吗
输出:
计数器类似于字典:参见https://docs.python.org/2/library/collections.html#collections.Counter
编辑:列表中的多个字符串:
输出:(删除0个条目)
相关问题 更多 >
编程相关推荐