【问题标题】:How do I fix this program so I can count the number of letters and how do I count words?如何修复这个程序,以便我可以计算字母的数量以及如何计算单词?
【发布时间】:2014-04-30 17:34:23
【问题描述】:

如何修复这个程序,以便我可以计算字母的数量以及如何计算单词?

import collections as c
text = input('Enter text')
print(len(text))
a = len(text)
counts = c.Counter(a)
print(counts)
spaces = counts(' ')
print(specific)
print(a-spaces)
#I want to count the number of letters so I want the amount of characters - the amount of             
#spaces.

【问题讨论】:

标签: python


【解决方案1】:

你应该将字符串直接传递给 Counter 的构造函数

cc = c.Counter( "this is a test" )
cc[" "] # will be 3

要做单词,只需按空格分隔(或者也可以是句号_

cc = c.Counter( "this is a test test".split( " " ) )
cc[ "test" ] # will be 2

【讨论】:

    【解决方案2】:

    要计算字符,可以使用正则表达式来删除任何非字母数字字符,即:

    import re
    print(re.sub("[\W]", "", text))
    

    您也可以使用re 模块来计算字数,方法是计算将字符串拆分为非字母数字字符时得到的非空字符串:

    print([word for word in re.split("[\W]", text) if len(word) > 0])
    

    如果您也想去除数字,只需使用 [\W\d] 而不是 [\W]

    您可以找到更多关于正则表达式here

    【讨论】:

      【解决方案3】:

      不要过度使用这个并使用一个好的旧列表理解:

      text = raw_input('Enter text') #or input(...) if you're using python 3.X
      number_of_non_spaces = len([i for i in text if i != " "])
      number_of_spaces = len(text) - number_of_non_spaces
      

      【讨论】:

        猜你喜欢
        • 2023-02-21
        • 2020-07-05
        • 1970-01-01
        • 2013-06-05
        • 1970-01-01
        • 1970-01-01
        • 2018-09-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多