Python【习题】:统计纯英文文本中总字数


人生苦短,我用Python

环境:Windows 10 64-bit, python == 3.6.4 , PyCharm CE == 2018.1
声明:学习资源来自于网络,这里是自己学习笔记总结与分享,每篇内容会随着学习的深入进行更新,如发现问题请评论留言。由于网络重复资源比较多,原作者不明,均未给出链接,实现代码根据自己的理解会重新编写,若原作者看到此文,请留言,我将标记文中代码来源。


题目:统计一个文件夹下,各个纯英文文本中单词总数。
本练习针对文件操作,要用到os, os.path模块中的相关内容:

  • os.path.basename(path):

Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split().
返回path最后的文件名。如果path以/或\结尾,那么就会返回空值

  • os.path.split(path) :

Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that.
将path分割成目录和文件名二元组返回。

  • os.path.splitext(path):

Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period.
分离文件名和扩展名

  • os.listdir(path):

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory.
返回指定目录下的所有文件和目录名

  • os.path.join(path, *paths)

Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths.
连接目录与文件名或目录

  • os.path.isdir():

Return True if path is an existing directory.
判断name是不是目录,不是目录就返回false

  • os.path.isfile():

Return True if path is an existing regular file.
判断name是不是文件,是则返回True, 不是在返回false。

  • endswith()方法:

Return True if the string ends with the specified suffix, otherwise return False.
str.endswith(suffix[, start[, end ]])
用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。

  • 分析:

定义两个函数,一是用于统计文本中字数的函数getcount(),二是用于获取指定目录下文件的函数getfiles().

  • 实现代码(运行OK):
import os, os.path

bookdir = r'D:\xiangmulixi\p04练习题'    # 指定目录  

# 定义统计函数
def getcount(path):
    if os.path.basename(path).endswith('.txt'):
        # os.path.basename(path):返回path中的文件名。
        with open(path,'r') as myfile:
            content = myfile.read()
            # read() 方法用于从文件读取指定的字节数,如果未给定或为负则读取所有。

            L = content.split()
            N = len(L)
            return N # 注:这里出现错误
            # Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串
            # 返回分割后的字符串列表。

def getfiles(dir):
    list = os.listdir(dir) # os.listdir(path):列举目录下的所有文件。返回的是列表类型。
    for i in range(len(list)):
        p = os.path.join(dir, list[i]) # # 将文件的相对路径转换成绝对路径
        # os.path.join(path1,path2,...):将path进行组合,若其中有绝对路径,则之前的path将被删除。

        if os.path.isdir(p): # os.path.isdir()函数检验给出的路径是否是目录
            getfiles(p)
        if os.path.isfile(p):# os.path.isfile()函数检验给出的路径是否是文件
            l = getcount(p)
            print('文件: %s  字数: %s 文件所在绝对路径: %s' % (os.path.basename(p), getcount(p),p))
# 调用函数
getfiles(bookdir)
  • 错误提示:

在上面的代码中,getcount(path)函数刚开始是按照网上教程中写的,如下:

def getcount(path):
    if os.path.basename(path).endswith('.txt'):
        with open(path,'r') as myfile:
            content = myfile.read()
            return  content.split()

直接返回content.split(),然后在getfiles(dir)函数中,用len(getcount(p))计算返回列表的长度,即为文本字数。但是,运行代码时,总是提示如下错误:

TypeError: object of type 'NoneType' has no len()

错误提示,return content.split()的返回值为NoneType,不支持任何运算也没有任何内建方法,所以不能使用len()计算。
修改代码,在getcount(path)函数中先计算好content.split()返回的列表的长度,然后将返回值N = len(L)作为函数的返回值返回。

待补充:return语句、函数返回值问题

你可能感兴趣的:(Python【习题】:统计纯英文文本中总字数)