0
点赞
收藏
分享

微信扫一扫

python 分析文本文件

Alex富贵 2022-05-18 阅读 63
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.

>>>




举报

相关推荐

0 条评论