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

如何用JES统计文件字符数及Python实现文件多维度统计与参数处理

Alright, let's tackle both of your questions step by step—first with JES (the student-friendly Python variant), then the command-line Python program for detailed file stats.

1. 用JES统计文件中的字符数

JES uses a simplified Python syntax, so this is straightforward. Here's a reusable function you can write and run in the JES editor:

def countFileCharacters():
    # 调用JES内置的文件选择器让用户选文件
    target_file = pickAFile()
    
    # 打开文件并读取内容,用with语句自动关闭文件
    with open(target_file, 'r') as file:
        file_content = file.read()
    
    # 统计总字符数(包含空格、换行、制表符等空白字符)
    total_chars = len(file_content)
    print(f"文件总字符数: {total_chars}")
    
    # 可选:只统计非空白字符
    non_whitespace_chars = len([char for char in file_content if not char.isspace()])
    print(f"非空白字符数: {non_whitespace_chars}")

在JES中运行的步骤:

  1. 打开JES,切换到Program标签页,粘贴上面的代码。
  2. 点击Load Program将代码加载到环境中。
  3. 在底部的Command Line输入countFileCharacters()并回车。
  4. 弹出文件选择框后,选中你的纯文本文件,统计结果就会立刻打印出来。
2. 带命令行参数的Python统计程序

这里我们用Python内置的sys模块处理命令行参数,同时添加错误处理,避免程序因为输入缺失或文件问题直接崩溃。完整代码如下:

import sys

def analyze_text_file(filename):
    try:
        # 用with语句自动关闭文件,避免资源泄漏
        with open(filename, 'r', encoding='utf-8') as file:
            lines = file.readlines()
            total_lines = len(lines)
            
            # 初始化各类计数器
            total_chars = 0
            vowels = 0
            consonants = 0
            lowercase = 0
            uppercase = 0
            
            # 定义元音集合,方便快速判断
            vowel_set = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
            
            # 逐行遍历统计各项指标
            for line in lines:
                total_chars += len(line)
                for char in line:
                    if char.isalpha():
                        # 区分元音和辅音
                        if char in vowel_set:
                            vowels += 1
                        else:
                            consonants += 1
                        # 区分大小写字母
                        if char.islower():
                            lowercase += 1
                        elif char.isupper():
                            uppercase += 1
            
            # 格式化输出统计结果
            print("=== 文件统计结果 ===")
            print(f"总行数: {total_lines}")
            print(f"总字符数(含空格、换行): {total_chars}")
            print(f"元音字母数: {vowels}")
            print(f"辅音字母数: {consonants}")
            print(f"小写字母数: {lowercase}")
            print(f"大写字母数: {uppercase}")
    
    # 优雅处理常见错误
    except FileNotFoundError:
        print(f"错误:文件 '{filename}' 不存在,请检查路径是否正确。")
    except PermissionError:
        print(f"错误:你没有读取 '{filename}' 的权限。")
    except Exception as e:
        print(f"发生意外错误: {str(e)}")

if __name__ == "__main__":
    # 检查用户是否提供了文件名参数
    if len(sys.argv) < 2:
        print("错误:未提供文件名参数。")
        print("使用方法: python file_analyzer.py 你的文本文件路径.txt")
    else:
        analyze_text_file(sys.argv[1])

使用这个程序的方法:

  1. 将代码保存为file_analyzer.py。
  2. 打开终端/命令提示符,导航到代码所在的文件夹。
  3. 运行命令:python file_analyzer.py your_text_file.txt
    • 如果忘记添加文件名,程序会输出清晰的错误提示和使用说明。
    • 它能处理文件不存在、权限不足等情况,不会直接崩溃。

补充说明:

  • 总字符数包含所有空白字符(空格、换行、制表符),如果需要排除这些,可以修改total_chars的计算逻辑,跳过空白字符。
  • 元音统计包含大小写,如果你只需要统计其中一种,可以调整vowel_set的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:37:33