You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PyCharm统计歌词.txt文件单词、字符及行数的代码问题求助

问题分析与代码修复

原代码的核心问题

  • 遍历文件行后,文件指针已移至末尾,后续infile.read()返回空字符串,导致单词数统计失效
  • len(data)统计的是字符数,并非单词数,概念混淆
  • 未实现字符数统计需求
  • 未使用上下文管理器,文件未显式关闭,存在资源泄漏风险

修复后的完整代码

# 用上下文管理器自动管理文件,避免资源泄漏
with open('lyrics.txt', 'r', encoding='utf-8') as infile:
    # 一次性读取所有行到列表,方便多维度统计
    lines_list = infile.readlines()
    
    # 统计行数
    total_lines = len(lines_list)
    # 统计字符数(包含换行符)
    total_chars = sum(len(line) for line in lines_list)
    # 统计单词数:合并内容后按空白分割,自动过滤多余空白
    full_content = ''.join(lines_list)
    total_words = len(full_content.split())

# 输出统计结果
print(f"The song has about {total_lines} lines in total.")
print(f"Love Me Harder has approximately {total_words} total words in the song.")
print(f"The song has approximately {total_chars} total characters (including line breaks).")

代码解释

  • with open(...):自动处理文件打开/关闭,无需手动调用close()
  • readlines():将文件所有行读取为列表,便于后续多次统计操作
  • total_lines = len(lines_list):直接获取行数,比逐行累加更高效简洁
  • total_chars = sum(len(line) for line in lines_list):累加每行的字符长度,包含换行符
  • full_content.split():按任意空白字符分割内容,自动过滤空值,得到的列表长度即为单词数

内容的提问来源于stack exchange,提问作者user29877730

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 13:05:01