Python: 用于计算txt文档的字数的小脚本

在一次实践中,需要计算txt文档(英文和数字)的字数,并且还要统计路径下的所有txt文档的字数总数。

本来以为很简单,但是在编写的过程中还是出现了一些问题。

首先就是,字数字符数是不一样的,不能简单的用len()。

根据英文的特性,每个单词都需要空格,我就选择使用split()函数来对已读的文本进行处理。

split()函数是以一个东西为分隔符,将字符串分开并存到列表里。如果括号里是空的,就默认以空格作为分隔符。

在将文本用split()函数处理后,通过读取列表的长度,就能得到字数。

但是这时又有新的问题,就是一些符号也会单独成为列表里的成员,如:

'Please input your ID number - targeted at the non-specialist' 就会出现单独的 ‘-’ 项。

这时把 ‘  !"#$%&()*+,-/:;<=>?@[\]^_`{|}  ’这些符号替换成空格就能有效的解决这个问题~

这个想法来自:Python实现统计文本文件字数的方法_-互联网文档类资源-CSDN下载

下面是代码,最后有我打包的exe程序的地址,可以不需要编译直接用~

觉得有帮助就点个赞吧~

### By Ziki ###
import os
import time

class counter:
    def signle_file_counter(self,filepath):
        
        with open(filepath,encoding='UTF-8',errors='ignore') as f:  #encoding method: UTF8, ignore errors                       
            txt=f.read()
            for symbol in '!"#$%&()*+,-/:;<=>?@[\]^_`{|}~': # Replace all symbols with spaces ' '  
                txt = txt.replace(symbol, ' ')
            self.words = txt.split() 
            #Use ' ' (space) as the separator to separate str and save all elements in list
            print(len(self.words)) # calculate the number of element -- word count
 
    def Scan_in_folder(self,folder_path): 
        #fileList=os.listdir(folder_path)
        self.total_count=0
        for path in os.listdir(folder_path):
            path=folder_path+'\\'+ path 
            self.signle_file_counter(path) # use single_file_counter def
            self.total_count+=len(self.words)
        print('The total words count in this folder is: ',self.total_count)

if __name__ == '__main__':
    mode=input("Type 1: count 1 file\nType 2: count all file in path\nMode chooses: ")
    if int(mode)==1:
        path=input("Please enter your file path:")
        a=counter()
        a.signle_file_counter(path)
        time.sleep(10)
    if int(mode)==2:
        path=input("Please enter your folder path:")
        a=counter()
        a.Scan_in_folder(path)
        time.sleep(10)

exe文件地址:Python:用于计算txt文档的字数的小脚本exe文件-Python文档类资源-CSDN文库

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值