python全项目实战系列(十四):文本字符类型计数

本系列旨在通过一系列由浅入深的python实战代码或项目,使普通人也能感受到编程的乐趣,编程能够在平时的工作生活上有所帮助。欢迎查看系列的开篇词和前面文章。

概述

在txt文本中输入内容,分别统计出其中英文字母、空格、数字和其它字符的个数。对有时候做文本的统计分析有用。

主要使用的python知识点有:

  1. 文件读写
  2. 字符拼接
  3. for循环遍历

实现思路是:

  1. 先读取有内容的TXT文档
  2. 去除换行符,拼接为一个字符串
  3. 遍历字符串,对符合的类型计数加1

代码实现过程

#打开文本文件,"C:\Users\zengz\Desktop\测试.txt"表示文件类型,'r+'表示读写模式,encoding='utf-8'表示utf-8编码f1 = open("C:\Users\zengz\Desktop\测试.txt",'r+', encoding='utf-8')#定义一个空字符串,用于拼接文本中的每一行f2 = ""# 遍历文件每一行,去除换行符,拼接为字符串for line in f1:    line = line.rstrip('
')    f2 += lineprint(f2)#设置计数的起始值,用letters,space,digit,others分别代表字母,空格,数字,其他letters = 0space = 0digit = 0others = 0#遍历字符串,统计结果for c in f2:    if c.isalpha():        letters += 1    elif c.isspace():        space += 1    elif c.isdigit():        digit += 1    else:        others += 1print('字母数 = %d,空格数 = %d,数字数 = %d,其他 = %d' % (letters,space,digit,others))

用来做测试的文件是测试.txt,是字符、数字和中文等混合的一段代码,里面内容如下

s = input('input a string:
')f1 = open("C:\Users\zengz\Desktop\测试.txt",'r+', encoding='utf-8')f2 = []for line in f1:    line = line.rstrip('
')    f2.append(line)#设置计时起始值,用letters,space,digit,others分别代表字母,空格,数字,其他letters = 0space = 0digit = 0others = 0for c in f2:    if c.isalpha():        letters += 1    elif c.isspace():        space += 1    elif c.isdigit():        digit += 1    else:        others += 1print('char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others))

结果是:字母数 = 282,空格数 = 102,数字数 = 14,其他 = 100,

s = input('input a string:
')f1 = open("C:\Users\zengz\Desktop\测试.txt",'r+', encoding='utf-8')f2 = []for line in f1:    line = line.rstrip('
')    f2.append(line)#设置计时起始值,用letters,space,digit,others分别代表字母,空格,数字,其他letters = 0space = 0digit = 0others = 0for c in f2:    if c.isalpha():        letters += 1    elif c.isspace():        space += 1    elif c.isdigit():        digit += 1    else:        others += 1print('char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others))字母数 = 282,空格数 = 102,数字数 = 14,其他 = 100


发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章