You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用Python去除文本文件中的随机换行符?

如何用Python去除文本文件中的随机换行符

先看你给出的文件示例,每条完整记录都是以数字(比如70)开头的,这种有明确特征的情况处理起来很方便。下面结合你提到的「合并fixed_inv.txtout.txt生成concat.txt」的需求,给你两种实用方案:

方案1:基于记录起始标识合并(适配你的场景)

利用每条记录固定的开头特征(比如以数字开头),我们可以逐行读取文件,把被随机拆分的行合并回原记录:

def fix_random_newlines(input_files, output_file):
    with open(output_file, 'w', encoding='utf-8') as out_f:
        current_record = ""
        # 遍历需要处理的输入文件
        for file_path in input_files:
            with open(file_path, 'r', encoding='utf-8') as in_f:
                for line in in_f:
                    cleaned_line = line.strip()
                    if not cleaned_line:
                        continue  # 跳过空行
                    # 判断当前行是否是新记录的开头(这里以数字开头为判断条件,可根据实际调整)
                    if cleaned_line[0].isdigit():
                        # 如果之前有未写完的记录,先写入文件
                        if current_record:
                            out_f.write(current_record + '\n')
                        current_record = cleaned_line
                    else:
                        # 如果是被拆分的行,追加到当前记录末尾
                        current_record += ' ' + cleaned_line
        # 写入最后一条记录
        if current_record:
            out_f.write(current_record + '\n')

# 按照你的需求执行:合并fixed_inv.txt和out.txt,同时修复换行,输出到concat.txt
fix_random_newlines(['fixed_inv.txt', 'out.txt'], 'concat.txt')

代码说明:

  • 先读取你指定的两个输入文件,逐行处理内容
  • 遇到以数字开头的行,就把之前累积的完整记录写入输出文件,然后开始新的记录
  • 如果行不是新记录的开头,就把它合并到当前正在累积的记录里
  • 最后不要忘记把最后一条记录也写入文件

方案2:基于行尾特征合并(通用场景)

如果你的文本没有明确的起始标识,而是随机换行在句子中间(比如行尾是...、逗号这类不完整标记),可以通过判断行尾特征来合并:

def fix_generic_newlines(input_files, output_file):
    with open(output_file, 'w', encoding='utf-8') as out_f:
        current_record = ""
        for file_path in input_files:
            with open(file_path, 'r', encoding='utf-8') as in_f:
                for line in in_f:
                    cleaned_line = line.strip()
                    if not cleaned_line:
                        continue
                    # 判断当前记录是否未结束(这里以行尾是...或逗号为例,可自定义)
                    if current_record and current_record.endswith(('...', ',')):
                        current_record += ' ' + cleaned_line
                    else:
                        if current_record:
                            out_f.write(current_record + '\n')
                        current_record = cleaned_line
        if current_record:
            out_f.write(current_record + '\n')

# 使用方式同上
fix_generic_newlines(['fixed_inv.txt', 'out.txt'], 'concat.txt')

小提示:

  • 你可以根据自己的实际文本调整判断条件,比如行尾是半角括号、连字符等,都可以加入判断逻辑
  • 测试时可以先拿一小段文本验证,确认合并效果符合预期后再处理完整文件

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

火山引擎 最新活动