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

如何遍历文本行并将长度不足50字符的行拼接在一起?

实现方案

方法1:使用while循环控制索引

完全可以用while循环实现,手动控制索引步进即可不受for循环自动迭代的限制,实现逻辑如下:

import sys

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        idx = 0
        total_lines = len(lines)
        while idx < total_lines:
            # 先去掉当前行末尾换行符,避免拼接后中间出现多余换行
            current_line = lines[idx].rstrip('\n')
            # 当前行长度满足要求直接写入
            if len(current_line) >= 50:
                f2.write(current_line + '\n')
                idx += 1
                continue
            # 长度不足,开始拼接后续行
            idx += 1
            while idx < total_lines and len(current_line) < 50:
                current_line += lines[idx].rstrip('\n')
                idx += 1
            # 拼接完成后统一写入
            f2.write(current_line + '\n')

上述代码的外层while循环负责遍历全行,遇到短行时进入内层循环持续取下一行拼接,直到拼接后长度≥50或者读完所有行再执行写入操作,完全匹配你的需求。

方法2:缓冲变量实现(无嵌套循环)

如果你不想用嵌套循环,也可以用临时缓冲变量存储待拼接的短行,逻辑更简洁:

import sys

buffer = ''
with open(sys.argv[1]) as f1, open(sys.argv[2], 'a') as f2:
    for line in f1:
        line = line.rstrip('\n')
        buffer += line
        if len(buffer) >= 50:
            f2.write(buffer + '\n')
            buffer = ''
    # 遍历完成后剩余的不足50字符的内容也写入
    if buffer:
        f2.write(buffer + '\n')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:24:07