代码:
# 读取一个文本,并且统计文本中单词的出现次数
def read_file():
# 在windows环境中的编码问题,指定utf-8
with open('F:/python源码/实验区/002.txt', 'r', encoding='utf-8') as f:
word = [] # 空列表用来存储文本中的单词
# readlins为分行读取文本,且返回的是一个列表,每行的数据作为列表中的一个元素:
for word_str in f.readlines(): # 如:["In this article, you will learn about Python closures, understand ",...]
# 因为原文中每个单词都是用空格 或者逗号加空格分开的,去除原文中的逗号
word_str = word_str.replace(',', '')
# strip去除每行字符串数据两边的空白字符
word_str = word_str.strip()
# 对单行字符串通过空格进行分割,返回一个列表
word_list = word_str.split(' ')
# 将分割后的列表内容,添加到word空列表中
w