如何用脚本转换大小写

wen 实用脚本 2

本文目录导读:

如何用脚本转换大小写

  1. Python 实现
  2. Shell 脚本
  3. JavaScript/Node.js
  4. 跨平台综合工具
  5. 使用示例
  6. 高级功能扩展

Python 实现

简单转换

# 文件转换脚本
def convert_case(text, mode='upper'):
    """转换文本大小写"""
    if mode == 'upper':
        return text.upper()
    elif mode == 'lower':
        return text.lower()
    elif mode == 'title':
        return text.title()
    elif mode == 'capitalize':
        return text.capitalize()
    elif mode == 'swapcase':
        return text.swapcase()
    else:
        return text
# 处理文件
def convert_file(filename, mode='upper'):
    with open(filename, 'r', encoding='utf-8') as f:
        content = f.read()
    converted = convert_case(content, mode)
    with open(filename.replace('.', '_converted.'), 'w', encoding='utf-8') as f:
        f.write(converted)
    print(f"转换完成!已保存为新文件")
# 使用示例
if __name__ == "__main__":
    text = "Hello World! This is a Test."
    print(f"大写: {convert_case(text, 'upper')}")
    print(f"小写: {convert_case(text, 'lower')}")
    print(f"标题: {convert_case(text, 'title')}")
    print(f"首字母大写: {convert_case(text, 'capitalize')}")
    print(f"反转大小写: {convert_case(text, 'swapcase')}")

命令行工具

#!/usr/bin/env python3
import sys
import argparse
def main():
    parser = argparse.ArgumentParser(description='文本大小写转换工具')
    parser.add_argument('input', help='输入文件或文本')
    parser.add_argument('-m', '--mode', default='upper',
                       choices=['upper', 'lower', 'title', 'capitalize', 'swapcase'],
                       help='转换模式')
    parser.add_argument('-f', '--file', action='store_true',
                       help='输入是文件路径')
    parser.add_argument('-o', '--output', help='输出文件路径')
    args = parser.parse_args()
    if args.file:
        with open(args.input, 'r', encoding='utf-8') as f:
            text = f.read()
    else:
        text = args.input
    converted = convert_case(text, args.mode)
    if args.output:
        with open(args.output, 'w', encoding='utf-8') as f:
            f.write(converted)
        print(f"已保存到 {args.output}")
    else:
        print(converted)
if __name__ == "__main__":
    main()

Shell 脚本

Bash 版本

#!/bin/bash
# 大小写转换脚本
convert_case() {
    local text="$1"
    local mode="$2"
    case "$mode" in
        upper)
            echo "$text" | tr '[:lower:]' '[:upper:]'
            ;;
        lower)
            echo "$text" | tr '[:upper:]' '[:lower:]'
            ;;
        title)
            echo "$text" | sed 's/.*/\L&/; s/[a-z]*/\u&/g'
            ;;
        swap)
            echo "$text" | tr 'a-zA-Z' 'A-Za-z'
            ;;
        *)
            echo "未知模式: $mode"
            echo "可用模式: upper, lower, title, swap"
            ;;
    esac
}
# 文件处理模式
convert_file() {
    local input_file="$1"
    local output_file="$2"
    local mode="${3:-upper}"
    if [[ ! -f "$input_file" ]]; then
        echo "错误: 文件不存在"
        exit 1
    fi
    cat "$input_file" | while read line; do
        convert_case "$line" "$mode"
    done > "$output_file"
    echo "转换完成!输出文件: $output_file"
}
# 主菜单
show_help() {
    echo "用法: $0 [文本] [模式]"
    echo "或: $0 -f [输入文件] [输出文件] [模式]"
    echo "模式: upper, lower, title, swap"
}
# 主程序
if [[ "$1" == "-f" ]]; then
    # 文件模式
    shift
    if [[ $# -eq 3 ]]; then
        convert_file "$1" "$2" "$3"
    elif [[ $# -eq 2 ]]; then
        convert_file "$1" "$2"
    else
        show_help
    fi
elif [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
    show_help
elif [[ $# -eq 0 ]]; then
    # 交互模式
    echo "请输入要转换的文本:"
    read text
    echo "选择模式 (upper/lower/title/swap):"
    read mode
    convert_case "$text" "$mode"
else
    # 直接命令行参数
    text="$1"
    mode="${2:-upper}"
    convert_case "$text" "$mode"
fi

JavaScript/Node.js

#!/usr/bin/env node
// 大小写转换函数
function convertCase(text, mode = 'upper') {
    switch(mode) {
        case 'upper':
            return text.toUpperCase();
        case 'lower':
            return text.toLowerCase();
        case 'title':
            return text.toLowerCase().replace(/\b\w/g, c => c.toUpperCase());
        case 'capitalize':
            return text.charAt(0).toUpperCase() + text.slice(1).toLowerCase();
        case 'camel':
            return text.replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) => {
                return index === 0 ? word.toLowerCase() : word.toUpperCase();
            }).replace(/\s+/g, '');
        default:
            return text;
    }
}
// 文件处理
const fs = require('fs');
const readline = require('readline');
function processFile(inputFile, outputFile, mode) {
    const rl = readline.createInterface({
        input: fs.createReadStream(inputFile),
        crlfDelay: Infinity
    });
    const output = fs.createWriteStream(outputFile);
    rl.on('line', (line) => {
        output.write(convertCase(line, mode) + '\n');
    });
    rl.on('close', () => {
        console.log(`文件处理完成: ${outputFile}`);
    });
}
// 命令行参数处理
const args = process.argv.slice(2);
const options = require('minimist')(args, {
    string: ['mode', 'input', 'output'],
    alias: { m: 'mode', i: 'input', o: 'output' }
});
if (options.input && options.output) {
    processFile(options.input, options.output, options.mode || 'upper');
} else if (args[0]) {
    console.log(convertCase(args[0], options.mode || 'upper'));
} else {
    console.log("用法: node case-converter.js [文本] -m [模式]");
    console.log("或: node case-converter.js -i [输入文件] -o [输出文件] -m [模式]");
    console.log("模式: upper, lower, title, capitalize, camel");
}

跨平台综合工具

#!/usr/bin/env python3
"""
综合大小写转换工具
支持: upper, lower, title, capitalize, swapcase, sentence
"""
import re
import sys
import argparse
def sentence_case(text):
    """首字母大写的句子"""
    return '. '.join(s.capitalize() for s in text.split('. '))
def convert_case(text, mode):
    """通用转换函数"""
    modes = {
        'upper': text.upper(),
        'lower': text.lower(),
        'title': text.title(),
        'capitalize': text.capitalize(),
        'swapcase': text.swapcase(),
        'sentence': sentence_case(text),
    }
    return modes.get(mode, text)
def main():
    parser = argparse.ArgumentParser(description='通用大小写转换工具')
    parser.add_argument('text', nargs='?', help='要转换的文本或文件路径')
    parser.add_argument('-m', '--mode', default='upper',
                       choices=['upper', 'lower', 'title', 'capitalize', 'swapcase', 'sentence'])
    parser.add_argument('-f', '--file', action='store_true', help='输入是文件路径')
    parser.add_argument('-o', '--output', help='输出文件')
    args = parser.parse_args()
    if not args.text:
        # 交互模式
        text = input("请输入要转换的文本: ")
        mode = input(f"选择模式 {['upper','lower','title','capitalize','swapcase','sentence']}: ") or 'upper'
        result = convert_case(text, mode)
    elif args.file:
        with open(args.text, 'r', encoding='utf-8') as f:
            text = f.read()
        result = convert_case(text, args.mode)
    else:
        result = convert_case(args.text, args.mode)
    if args.output:
        with open(args.output, 'w', encoding='utf-8') as f:
            f.write(result)
        print(f"结果已保存到: {args.output}")
    else:
        print(result)
if __name__ == "__main__":
    main()

使用示例

# Python 命令行使用
python case_converter.py "Hello World" -m upper
python case_converter.py -f input.txt -o output.txt -m title
# Bash 使用
./case_converter.sh "hello world" upper
./case_converter.sh -f input.txt output.txt lower
# Node.js 使用
node case-converter.js "Hello World" -m title
node case-converter.js -i input.txt -o output.txt -m camel

高级功能扩展

# 批量文件处理
def batch_convert(directory, pattern='*.txt', mode='upper'):
    import glob
    import os
    files = glob.glob(os.path.join(directory, pattern))
    for file in files:
        base, ext = os.path.splitext(file)
        convert_file(file, f"{base}_converted{ext}", mode)
    print(f"已转换 {len(files)} 个文件")
# 剪贴板集成
def from_clipboard():
    try:
        import pyperclip
        text = pyperclip.paste()
        result = convert_case(text, mode)
        pyperclip.copy(result)
        print("转换结果已复制到剪贴板")
    except ImportError:
        print("请安装: pip install pyperclip")

这些脚本可以满足大部分大小写转换需求,选择哪种取决于你的使用场景:

  • 简单一次性转换:用 Python 或 Bash 单行命令
  • 批量文件处理:用 Python 脚本
  • 交互式使用:用 Bash 菜单或 Python CLI 工具

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