python的split()函数用来计算文本中单词的个数

#计算文件大约包含多少个单词
filename='alice.txt'
try:
    with open(filename,encoding='utf-8') as f_obj:
        contents=f_obj.read()
except FileNotFoundError as e:
    msg=" sorry "+filename +"not exist"
    print(msg)
else:
    words=contents.split()# split()可以以空格为分隔符,把字符串拆分,储存在列表中
    num_words=len(words)
    print("The file "+filename +"has about "+str(num_words)+" words")

#可以包装成可以计算包含多少个单词的函数
def count_words(filename):
    """计算一个文件大约有多少个单词"""
    try:
        with open(filename,encoding='utf-8')as f_obj:
            contents=f_obj.read()
    except FileNotFoundError as e:
        msg=" sorry "+filename +"not exist"
        print(msg)
    else:
        words=contents.split()# split()可以以空格为分隔符,把字符串拆分,储存在列表中
        num_words=len(words)
        print("The file "+filename +"has about "+str(num_words)+" words")


filename='alice.txt'
count_words(filename)


你可能感兴趣的:(python的split()函数用来计算文本中单词的个数)