【问题标题】:Counting letters numbers and punctuation in a string计算字符串中的字母数字和标点符号
【发布时间】:2011-10-21 14:34:35
【问题描述】:

如何编写一个程序来计算字符串中的字母、数字和标点符号(分别)?

【问题讨论】:

  • 到目前为止你尝试过什么?请表明您已经付出了一些努力来尝试自己回答这个问题。
  • “分开”是什么意思?

标签: python


【解决方案1】:

对于更精简/更快的版本,还有

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

使用一套应该会让你的速度有所提升。

还取决于字符串的大小,我认为您也应该通过过滤器获得内存优势。

【讨论】:

  • 我更喜欢这个解决方案。最佳答案是 lambdas 有点混乱。
  • 这里不需要列表推导,简单的生成器表达式不仅更短而且更高效。
  • 但不是更快。生成器速度较慢,因为它们...生成。所以我说更快
  • 更简洁地说,您可以为标点符号/数字/字母生成一个正则表达式 - 它比这里的其他任何东西都快(取决于他们如何实现正则表达式)
【解决方案2】:
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 我认为。而且,括号不匹配。
  • 你说得对,我写了大约 10 秒,因为我很着急,固定 =P
  • 另外请注意,在 Python 3+ 中,filter 返回一个过滤器对象,它不支持 len。也许list(filter(...)) 的兼容性更好。
  • @utdemir 很高兴知道,我仍然懒得安装和使用 Py3,但我知道我必须 ^^'
【解决方案3】:
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)

【讨论】:

    【解决方案4】:
    >>> 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

    http://docs.python.org/library/functions.html#len

    http://docs.python.org/library/functions.html#filter

    【讨论】:

      【解决方案5】:

      要遍历字符串,您可以使用 for 循环:

      for c in "this is a test string with punctuation ,.;!":
          print c
      

      输出:

      t
      h
      i
      s
      ...
      

      现在,您所要做的就是计算出现次数...

      【讨论】:

      • a = "我不会再将作业作为问题发布到操作系统上。"
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 2022-01-07
      相关资源
      最近更新 更多