使用python批量统计小说字数

您所在的位置:网站首页 批量统计word字数 使用python批量统计小说字数

使用python批量统计小说字数

2023-12-08 05:18| 来源: 网络整理| 查看: 265

我们可以编写函数来通过对文件字符串的split和长度计算(len)来获取个txt文件的字数。

def count_words(filename): try: with open(filename,'r',encoding='utf-8') as f: contents = f.read() except FileNotFoundError: return(f"The file {filename} doesn't exit. Please check!") except UnicodeDecodeError: return(f"Please endoce the file with utf-8 format.") words = contents.split() return len(words)

注意到,我们在其中使用了try-except语句来处理了找不到文件时的异常(FileNotFound)。

这样,我们可以定义小说txt文件列表,然后通过for循环来对这些文件进行操作,依次统计出各个小说的字数了,如果文件不存在,就会优雅地报错并且不影响后续程序的执行。

book_list = ['alice.txt','princess.txt','siddhartha.txt','moby.txt'] for book in book_list: print(count_words(book))

在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3