txt 文本对齐,重新排序

import sys
import os

def process_file(input_file):
    # 读取输入文件
    with open(input_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    # 计算单词的最大长度
    max_word_length = max(len(line.split()[0]) for line in lines)
    
    # 处理每行,替换空格为制表符
    processed_lines = []
    for line in lines:
        parts = line.split()
        if len(parts) == 2:
            word, translation = parts
            # 计算需要的空格数量
            space_count = max_word_length - len(word)
            spaces = ' ' * space_count  # 用空格来确保对齐
            processed_line = f"{word}{spaces} {translation}\n"
            processed_lines.append(processed_line)
    
    # 自动生成输出文件名
    base_name = os.path.splitext(input_file)[0]  # 获取文件名不带扩展名部分
    output_file = f"{base_name}_align.txt"  # 输出文件名为源文件名+_align.txt
    
    # 将处理后的内容写入输出文件
    with open(output_file, 'w', encoding='utf-8') as f:
        f.writelines(processed_lines)
    
    print(f"File processed and saved to {output_file}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python script.py <input_file>")
        sys.exit(1)
    
    input_file = sys.argv[1]
    process_file(input_file)
import random
import sys
from datetime import datetime
import os

def process_file(input_filename):
    with open(input_filename, 'r', encoding='utf-8') as infile:
        lines = infile.readlines()

    # 提取每行的左边部分,即英文单词
    words = [line.split()[0] for line in lines]

    # 打乱顺序
    random.shuffle(words)

    # 获取当前时间,作为新文件名
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')

    # 提取源文件的文件名(不包含路径)
    base_filename = os.path.splitext(os.path.basename(input_filename))[0]

    # 生成新文件名
    output_filename = f"{base_filename}_{timestamp}.txt"

    # 保存新的文件
    with open(output_filename, 'w', encoding='utf-8') as outfile:
        for word in words:
            outfile.write(word + '\n')

    print(f"Processed file saved as {output_filename}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python script.py <input_filename>")
    else:
        input_filename = sys.argv[1]
        process_file(input_filename)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值