【发布时间】:2011-10-21 14:34:35
【问题描述】:
如何编写一个程序来计算字符串中的字母、数字和标点符号(分别)?
【问题讨论】:
-
到目前为止你尝试过什么?请表明您已经付出了一些努力来尝试自己回答这个问题。
-
“分开”是什么意思?
标签: python
如何编写一个程序来计算字符串中的字母、数字和标点符号(分别)?
【问题讨论】:
标签: python
对于更精简/更快的版本,还有
count = lambda l1,l2: sum([1 for x in l1 if x in l2])
例如:
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
使用一套应该会让你的速度有所提升。
还取决于字符串的大小,我认为您也应该通过过滤器获得内存优势。
【讨论】:
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)
【讨论】:
sum 应该是 len 我认为。而且,括号不匹配。
list(filter(...)) 的兼容性更好。
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)
【讨论】:
>>> 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
【讨论】:
要遍历字符串,您可以使用 for 循环:
for c in "this is a test string with punctuation ,.;!":
print c
输出:
t
h
i
s
...
现在,您所要做的就是计算出现次数...
【讨论】: