在一次实践中,需要计算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)