python 分析文本文件

def count_words(filename):#统计指定文件单词的数量
    """Count the approximate number of words in a file."""
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        pass
    else:
        words = contents.split()#以空格分隔形成列表
        num_words = len(words)#统计列表元素的个数
        print(f"The file {filename} has about {num_words} words.")

filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)

结果:

The file alice.txt has about 29465 words.
The file siddhartha.txt has about 42172 words.
The file moby_dick.txt has about 215830 words.
The file little_women.txt has about 189079 words.
>>>

posted @ 2021-01-03 13:51  myrj  阅读(367)  评论(0编辑  收藏  举报