我正在尝试计算日志文件内容中的空格数。
我参考了多个网站,提供的解决方案如下:
datafile = input("enter the file name:")
k=0
with open(datafile, 'r') as openedfile:
for line in openedfile:
words = line.split()
for i in words:
for letter in i:
if(letter.isspace):
k=k+1
print (k)
但是此代码打印文件中的字母数。
我尝试了以下代码:
fname = input("Enter file name: ")
k = 0
with open(fname, 'r') as f:
for line in f:
for a in line:
if (a.isspace()) == True:
k = k+1
print("Occurrences of blank spaces:")
print(k)
这是将缩进(第一行的末尾和第一行的星号(视为空格。
我希望代码只打印文件内容中的空格数(不包括逐行缩进(
total_spaces = 0
with open(fname, 'r') as f:
total_spaces = sum([len(list(filter(lambda c: c == ' ', line))) for line in f])
print(total_spaces)
您可以计算应用于空格的 .split()
方法产生的项目数(减去 1,因为项目将比空格多一个(。
n_space = len(open('text.txt', 'r').read().split(' ')) - 1
使用下面的text.txt
文件,代码成功计算了 7 个空格。
Lorem ipsum dolor sit amet, consectetur adipiscing elit
编辑
如果您有多个要视为空格的分隔符(如双倍空格或制表符(,只需在拆分和计数之前将它们替换为简单空格即可
text = open('text.txt', 'r').read().replace(' ', ' ').replace('t', ' ')
n_spaces = len(text.split(' ')) - 1
您可以使用.strip()
去除前导空格和尾随空格:
...
for a in line.strip():
...
使用 Regex --> re.findall(r"s", line.strip())
.
前任:
import re
with open(filename) as infile:
print(sum(len(re.findall(r"s", line.strip())) for line in infile))
-
s
-->表示文本中的空格