【问题标题】:Count words and spaces with a multiple line text用多行文本计算单词和空格
【发布时间】:2017-11-06 19:56:57
【问题描述】:

我需要通过在Python中定义一个函数来计算下面所示文本的单词数和空格数。我尝试使用split(" ") 命令,但由于文本位于两行不同的行中,我不知道该怎么做。有人可以帮帮我吗?

text1 = "A sentence is a group of words that makes complete sense, \n contains a main verb, and begins with a capital letter."

【问题讨论】:

标签: python count counter words


【解决方案1】:

你可以试试下面的

单词

print len(text1.replace('\\', '').split())

空格

print text1.count(' ')

【讨论】:

  • err,反斜杠替换是旧版本问题的残余。它不再有用了。
  • 感谢您的帮助。然而,在计算空格的情况下,没有必要指定 Python 不计算 \n 之后第一行中的空格?提前致谢
【解决方案2】:

另一种计算字数的方法如下:

打印 len(text1.split())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多