txt文件Python中位数和空格的计数

2024-09-27 21:26:43 发布

您现在位置:Python中文网/ 问答频道 /正文

为此,我要创建一个代码,它计算txt文件中“0”的数量,也计算空白空格/空格的数量。我已经完成了大部分内容,但我不知道如何计算空格

fname=open("done.txt", 'r')
text = fname.read()
count = 0
countBlank=0
for line in text:
    for char in line:
        if char.isdigit()==True:
            if char == "0":
                count = count + 1
print sum(count+countBlank)

Tags: 文件代码textintxtfor数量if
3条回答

还有builtin sum和生成器:

text = fname.read()
total = sum(char.isspace() or char == "0" for char in text)
zero_count = sum(char == "0" for char in text)
space_count = sum(char.isspace() for char in text)

我脑海中第一个闪现的方式是:

with open(r'input.txt', 'r') as f:
    count = len(''.join(c for line in f for c in line if c in ('0', ' ')))

这将创建一个字符串,该字符串只包含您要查找的字符的,然后确定该字符串的长度。在

可以使用str.isspace检查空间,如果只想计数“0”,则只需检查"0"。在

if char == "0": 
      zero_count += 1
elif char.isspace():
     spc_count += 1

如果不需要单独计数,请使用or

^{pr2}$

或用于:

   total += char in {" ","0"}

或者使用Counterdict:

from collections import Counter
with open("done.txt", 'r') as f:
     cn = Counter(f.read())
     print(cn[" "])
     print(cn["0"])
     print(cn[" "] + cn["0"])

正如您所知,text.split()在代码中什么也不做,如果分割文本,那么您将丢失所有空格。另外,str.isspace也适用于制表符等。。因此,取决于你的文件中有什么将决定你可以或不能使用

相关问题 更多 >

    热门问题