Python读取文件并统计单词数时出现计数为0的问题求助
问题解决:同时读取文件内容并统计单词数
问题核心在于文件读取指针的位置:第一次调用file.read()时,文件指针会移动到文件末尾,第二次调用file.read()只能读到空内容,因此单词统计结果为0。
修正后的代码
file = open('file_lab.txt', 'rt') # 将文件内容一次性读取到变量中,复用该变量完成打印和统计操作 data = file.read() print(data) words = data.split() print('Number of words in text file:', len(words))
预期输出
This is a files that has different lengths of lines Number of words in text file: 9
另外推荐使用with语句管理文件,它会自动完成文件关闭操作,避免资源泄漏:
with open('file_lab.txt', 'rt') as file: data = file.read() print(data) words = data.split() print('Number of words in text file:', len(words))
内容的提问来源于stack exchange,提问作者kieraaa1
相关产品推荐
相关产品推荐

