失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Python: 用于计算txt文档的字数的小脚本

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

时间:2021-05-24 17:22:27

相关推荐

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

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

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

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

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

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

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

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

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

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

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

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

觉得有帮助就点个赞吧~

### By Ziki ###import osimport timeclass 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 listprint(len(self.words)) # calculate the number of element -- word countdef Scan_in_folder(self,folder_path): #fileList=os.listdir(folder_path)self.total_count=0for path in os.listdir(folder_path):path=folder_path+'\\'+ path self.signle_file_counter(path) # use single_file_counter defself.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文库

如果觉得《Python: 用于计算txt文档的字数的小脚本》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。