php统计空格,python - 如何统计 文本 中的 空格数 和 数字 的个数 ?

Python新手求教,还望详解!

想要实现实现的功能:

统计一个文本中的空格数和数字的个数。

具体如下:

文本:

4 8 15 16 23 42 520 I LOVE LOST.

得出结果:

number_counts = 7

space_counts = 13 #42和520之间有5个空格,4~42之间都是一个1个空格

更新部分:

根据 @banagoo 提高的答案,我的代码:(还是有问题?)

import os

os.chdir('/Users/apple/Desktop/Python/chapter')

file_name = "lost.txt"

space_counts = 0

number_counts = 0

with open(file_name, 'r') as f:

for line in f:

space_counts += len( line.split() )

number_list = [x for x in line.split() if x.isdigit()]

number_counts = len(number_list)

print "space_counts", space_counts

print "number_counts",number_counts

文本:

4 8 15 16 23 42 520 I LOVE LOST.

4 8 15 16 23 42 520 I LOVE YOU.

发现答案不对呀!求指教?

70a0e015846ac278b0f47bab48265cd9.png

谢谢 @banagoo 的帮助,可运行的代码如下:

import os

os.chdir('/Users/apple/Desktop/Python/chapter')

file_name = "lost.txt"

space_counts = 0

number_counts = 0

number_list = []

with open(file_name, 'r') as f:

for line in f:

line = line.strip()

space_split_list = line.split(' ')

space_counts += len(space_split_list) - 1

for word in space_split_list:

if word.isdigit():

number_list.append(word)

number_counts = len(number_list)

print "space_counts", space_counts

print "number_counts", number_counts

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值