python-3.x - 计算文本中不包括缩进的空格数

标签 python-3.x

我正在尝试计算日志文件内容中的空格数。

我引用了多个网站,提供的可能的解决方案如下:


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/

相关文章:

python - Python 中的自定义异常

python-3.x - 为什么python中的id()也返回一个字面值

python - Kivy-python : duplicate image on texture

python - 'str' 对象在 Python3 中没有属性 'decode'

python-3.x - python的电报内联键盘中的换行符

python - 无法解决以10为底的int()的基本错误无效文字

Python 全局热键

python - 在python中循环遍历真值数组并用另一个数组中的组件替换真值

python - *** ValueError : invalid literal for int() with base 10: '#'

python - 函数参数名以下划线开头