当前位置:   article > 正文

python练习题:文本分析(1)——统计文件中的字符_classify_char

classify_char

这题就是填一些简单代码,相信来认真看代码的找问题应该是第三个测试没有出来(空格数目对不上),我一开始也被摆了一道,后面仔细排查了下,发现题目里的space只针对空格(老坑了),所以把c.isspace()换成c==" "即可

这里就不上题目了(反正没啥用),直接上代码

  1. import string
  2. def read_file(file):
  3. """接收文件名为参数,读取文件中的数据到字符串中,返回这个字符串"""
  4. with open(file, 'r', encoding='utf-8') as f:
  5. return f.read()
  6. def classify_char(txt):
  7. """接收字符串为参数,依序返回大写字母、小写字母、数字、空格、和其他字符数量"""
  8. upper, lower, digit, space, other = 0, 0, 0, 0, 0
  9. for c in text:
  10. if c.isupper():
  11. upper+=1
  12. elif c.islower():
  13. lower+=1
  14. elif c.isdigit():
  15. digit+=1
  16. elif c==" ":
  17. space+=1
  18. else:
  19. other+=1
  20. #####
  21. return upper, lower, digit, space, other
  22. if __name__ == '__main__':
  23. filename = input() # 读入文件名
  24. text = read_file(filename) # 调用函数读文件中的内容为字符串
  25. classify = classify_char(text) # 调用函数分类统计字符数量
  26. print('大写字母{}个,小写字母{}个,数字{}个,空格{}个,其他{}个'.format(*classify))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/389542
推荐阅读
相关标签
  

闽ICP备14008679号