为此,我要创建一个代码,它计算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:
还有builtin sum和生成器:
我脑海中第一个闪现的方式是:
这将创建一个字符串,该字符串只包含您要查找的字符的,然后确定该字符串的长度。在
可以使用
str.isspace
检查空间,如果只想计数“0”,则只需检查"0"
。在如果不需要单独计数,请使用
^{pr2}$or
:或用于:
或者使用Counterdict:
正如您所知,
text.split()
在代码中什么也不做,如果分割文本,那么您将丢失所有空格。另外,str.isspace
也适用于制表符等。。因此,取决于你的文件中有什么将决定你可以或不能使用相关问题 更多 >
编程相关推荐