有没有办法压缩文本文件并删除空白行以便我计算文本中的空格?我有一个大约 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/