如下代码示例中,从文件中读取内容,然后将内容用split()函数分割,转换成列表,然后求列表的长度,就可以计算出文件大约包含多少个单词:
filename = 'data/UserMapper.xml'
try:
with open(filename, encoding='utf-8') as obj:
contents = obj.read()
except FileNotFoundError:
print(f'文件 {filename} 不存在!')
else:
# 计算该文件大体包含多少个单词
words = contents.split()
num = len(words)
print(f"about {num} words")
运行输出: