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

时间:2018-10-30 09:56:21

标签: 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

致谢

6 个答案:

答案 0 :(得分:1)

我将使用正则表达式解决此问题:

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')将被忽略。

答案 1 :(得分:1)

下面的这段代码分别计算空格数和行数。 希望这会有所帮助。

import re
count = 0
fname = input("Enter file name: ")

with open(fname,'r') as f:       #This counts the blank space
    print("Number of space: ", len(re.findall(r' ', f.read())))

with open(fname, 'r') as f:      #This counts the number of lines
    for line in f:
        count += 1
print("Total number of lines is:", (count - 1))

答案 2 :(得分:0)

您需要做的是计算单词数。空格数总是少于单词数一。

def spaces():
number_of_spaces = 0
    with open(TEXT, "r") as fh:
        words = [word for line in fh for word in line.split()]
        number_of_spaces = len(words-1)
return number_of_spaces 

答案 3 :(得分:0)

我可以建议按空格分割行,并让您的空格计数为结果数组的长度减一吗?

sample_text = """A simple test to see how many
spaces are in these lines of text"""

amount_of_spaces = len(sample_text.split(' ')) - 1
print(amount_of_spaces)
>>> 12

这也很好地处理了文本中的尾随空格或多个后续空格

答案 4 :(得分:0)

如果要查找空格,为什么不使用正则表达式:

import re
amountOfWhitespaces = len(re.findall('\x20', yourString)
print(amountOfWhitespaces)

答案 5 :(得分:0)

如果要分别计算所有空格,可以使用count中的内置函数String

with open(TEXT, "r") as fh: 
    count = sum(line.strip().count(' ') for line in fh)

注意:这确实会使用strip尾随空格,如您所说,您只想计算单词之间的空格。它还以这种方式处理包含空格的空行。它将双空格视为两个单独的空格,并且忽略制表符'\t'

这是否取决于您要执行的操作。