python-英文统计

程序实现对特定英文文章(文本文件)的单词数和有效行数的统计,其中要求空行不计数

 

代码:

import re

file = "123.txt"
line_num = 0  # 行数
word_num = 0  # 单词个数

with open(file, 'rb')as f:
    for line in f:
        regEx = "[!\#$%&'()*+,-./:;<=>?@[\]^_`{|}~]"  # 将特殊字符转空格
        ss = re.sub(regEx, " ", str(line, "utf-8"))
        words = ss.split() 
        if words:
            line_num += 1
        word_num += len(words)

print("行数:", line_num)
print("单词数:", word_num)

posted @ 2022-04-19 14:05  睡觉不困  阅读(175)  评论(0编辑  收藏  举报