Python - 计算空格,而不是空行

标签 python loops character

有没有办法压缩文本文件并删除空白行以便我计算文本中的空格?我有一个大约 20 行的文本文件,我想计算单词之间的空格。但我想我也数了白线,因为我在柜台上得到了超过 800 条白线。

def spaces():
"""
Counting spaces
"""

number_of_spaces = 0

with open(TEXT, "r") as fh:
    for line in fh:
        space = line.split()
        for i in space:
            for char in i:
                if char.isspace():
                    number_of_spaces += 1

return number_of_spaces

问候

最佳答案

我会使用正则表达式来解决这个问题:

import re

def spaces(file_name):
    """Return the number of spaces in the text."""
    with open(file_name, 'r') as f:
        return len(re.findall(r' +', f.read()))

正则表达式r' +' 将查找一个或多个连续的空格。所以双空格只算作一个。其他空白字符(如 '\t')将被忽略。

关于Python - 计算空格,而不是空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53061642/

相关文章:

python - 类型错误 : 'type' object has no attribute '__getitem__' in pandas DataFrame

Python psql 分成各自的列

使用 pthreads 在 C 中将顺序循环转换为并行循环

R:循环列表列表以检索包含命中的子列表的标题

Java 递归 System.out.println()

python - 使用 bot Telegram API 转发包含多个媒体文件的消息

python - install.sh 在 OS X 上安装 Google Cloud SDK 时出现 python 问题

loops - 在单链接列表中检测循环的开始?

javascript - 如何通过添加空格使所有文件名的长度相同?

php - 如何将包含任何字符的 NSString 获取到我的数据库中?