脚本怎样统计文本字数

wen 实用脚本 28

本文目录导读:

脚本怎样统计文本字数

  1. Python 脚本(最常用)
  2. Bash Shell 脚本(Linux/Mac)
  3. JavaScript 脚本(网页/Node.js)
  4. 单行命令(快速统计)
  5. 在线工具方式(无需安装)
  6. 注意事项

Python 脚本(最常用)

基础字数统计

def count_characters(text):
    # 统计所有字符数(含空格和标点)
    total_chars = len(text)
    # 统计不含空格的字符数
    chars_no_space = len(text.replace(' ', ''))
    # 统计中文字符数(仅统计汉字)
    chinese_chars = sum(1 for char in text if '\u4e00' <= char <= '\u9fff')
    return {
        'total': total_chars,
        'no_space': chars_no_space,
        'chinese': chinese_chars
    }
# 示例使用
text = "Hello, 世界!这是一个测试文本。"
result = count_characters(text)
print(f"总字符数: {result['total']}")
print(f"不含空格: {result['no_space']}")
print(f"中文字数: {result['chinese']}")

从文件读取统计

def count_file_characters(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    return count_characters(content)
# 使用
file_result = count_file_characters('my_document.txt')

Bash Shell 脚本(Linux/Mac)

#!/bin/bash
# 统计文本字数脚本
# 读取输入文本
if [ -f "$1" ]; then
    text=$(cat "$1")
else
    text="$1"
fi
# 统计各种字数
total_chars=$(echo -n "$text" | wc -m)
chinese_chars=$(echo "$text" | grep -oP '[\x{4e00}-\x{9fff}]' | wc -l)
words=$(echo "$text" | wc -w)
echo "总字符数: $total_chars"
echo "中文字数: $chinese_chars"
echo "单词数: $words"

使用方式:

chmod +x char_count.sh
./char_count.sh "你的文本"
# 或
./char_count.sh my_file.txt

JavaScript 脚本(网页/Node.js)

浏览器控制台使用

// 在浏览器控制台直接输入
function countChars(text) {
    return {
        total: text.length,
        noSpace: text.replace(/\s/g, '').length,
        chinese: (text.match(/[\u4e00-\u9fff]/g) || []).length
    };
}
// 使用
countChars("Hello, 世界!")

Node.js 命令行工具

// char-counter.js
const fs = require('fs');
const filePath = process.argv[2];
if (filePath) {
    const text = fs.readFileSync(filePath, 'utf-8');
    console.log(`总字符数: ${text.length}`);
    console.log(`不含空格: ${text.replace(/\s/g, '').length}`);
    console.log(`中文字数: ${(text.match(/[\u4e00-\u9fff]/g) || []).length}`);
}

运行:node char-counter.js myfile.txt

单行命令(快速统计)

Linux/Mac 终端

# 统计文件字符数(含换行)
wc -m file.txt
# 统计中文字符数
grep -oP '[\x{4e00}-\x{9fff}]' file.txt | wc -l
# 统计单词数
wc -w file.txt

Windows PowerShell

# 统计字符数
(Get-Content file.txt | Out-String).Length
# 统计中文字符
(Select-String -Path file.txt -Pattern "[\u4e00-\u9fff]" -AllMatches).Matches.Count

在线工具方式(无需安装)

使用在线文本统计工具:

注意事项

  1. 编码问题:中文文本建议使用 UTF-8 编码
  2. 统计标准:不同软件对"字数"定义不同(字符/单词/汉字)
  3. 特殊字符:换行符、制表符可能被计入或排除
  4. 性能:大文件建议使用流式处理而非一次性读取

根据你的具体需求(文件类型、统计维度、运行环境)选择合适的方案。

抱歉,评论功能暂时关闭!