如何统计 文本 中的 空格数 和 数字 的个数 ?

Elephant_小象
  • 12

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.

发现答案不对呀!求指教?
运行结果

谢谢 @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
回复
阅读 9k
2 个回答
不卷毛
  • 355
✓ 已被采纳
input_str = '4 8 15 16 23 42     520 I LOVE LOST.'
space_split_list = input_str.split(' ')
space_counts = len(space_split_list) - 1
number_list = [x for x in space_split_list if x.isdigit()]
number_counts = len(number_list)

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:
        line = line.strip()  # 每行行首,行尾的空格会被忽略
        space_split_list = line.split(' ')
        space_counts += len(space_split_list) - 1
        number_list = [x for x in space_split_list if x.isdigit()]
        number_counts = len(number_list)

print "space_counts", space_counts
print "number_counts", number_counts

可以尝试用正则表达式。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进