如何编写一个在字符串中对字母,数字和标点符号(单独)进行计数的程序?
答案 0 :(得分:5)
对于稍微更精简/更快的版本,还有
count = lambda l1,l2:sum(如果x在l2中,则为l中的x为1)
所以例如:
count = lambda l1,l2: sum([1 for x in l1 if x in l2])
In [11]: s = 'abcd!!!'
In [12]: count(s,set(string.punctuation))
Out[12]: 3
使用套装可以在某种程度上提高你的速度。
也取决于字符串的大小我认为你应该获得对过滤器的记忆优势。
答案 1 :(得分:3)
import string
a = "I'm not gonna post my homework as question on OS again, I'm not gonna..."
count = lambda l1, l2: len(list(filter(lambda c: c in l2, l1)))
a_chars = count(a, string.ascii_letters)
a_punct = count(a, string.punctuation)
答案 2 :(得分:1)
count_chars = ".arPZ"
string = "Phillip S. is doing a really good job."
counts = tuple(string.count(c) for c in count_chars)
print counts
(2,2,1,1,0)
答案 3 :(得分:1)
>>> import string
>>> import operator
>>> import functools
>>> a = "This, is an example string. 42 is the best number!"
>>> letters = string.ascii_letters
>>> digits = string.digits
>>> punctuation = string.punctuation
>>> letter_count = len(filter(functools.partial(operator.contains, letters), a))
>>> letter_count
36
>>> digit_count = len(filter(functools.partial(operator.contains, digits), a))
>>> digit_count
2
>>> punctuation_count = len(filter(functools.partial(operator.contains, punctuation), a))
>>> punctuation_count
3
http://docs.python.org/library/string.html
http://docs.python.org/library/operator.html#operator.contains
http://docs.python.org/library/functools.html#functools.partial
答案 4 :(得分:0)
要遍历字符串,您可以使用for循环:
for c in "this is a test string with punctuation ,.;!":
print c
输出:
t
h
i
s
...
现在,您所要做的就是计算事件...