我正在尝试计算日志文件内容中的空格数。
我引用了多个网站,提供的可能的解决方案如下:
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)
关于python-3.x - 计算文本中不包括缩进的空格数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56679868/