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

Python修复引号内换行代码未输出最后一行问题排查及优化求助

问题原因

你的代码核心问题是混用了for line in f文件迭代和next(f)手动读行:next(f)读取的行不会再进入for循环的迭代序列。你测试文件中倒数第二行ing"的双引号计数为奇数,触发第二个if分支后next(f)把最后一行Teste1提前读走了,这行永远不会进入for循环处理,自然不会被打印。

修复后的原逻辑实现
import re
from collections import Counter

path = "替换为你的文件路径"
line_buffer = ""
with open(path, 'r', encoding='utf-8') as f:
    for line in f:
        current_line = line.strip()
        # 有未闭合的引号,先拼到缓存
        if line_buffer:
            line_buffer += " " + current_line
        else:
            line_buffer = current_line
        # 检查当前缓存的引号是否成对
        quote_count = Counter(line_buffer)['"']
        if quote_count % 2 == 0:
            # 成对就处理输出,清空缓存
            res = re.sub(r'"[^"]+"', lambda m: m.group(0).replace("\n", ""), line_buffer)
            print(res)
            line_buffer = ""
# 循环结束后如果还有未处理的缓存(异常场景补输出)
if line_buffer:
    print(line_buffer)
更简便的实现方案

完全可以模仿你给出的awk命令逻辑,实现更简洁的版本,无需逐行判断计数:

path = "替换为你的文件路径"
with open(path, 'r', encoding='utf-8') as f:
    content = f.read()
parts = content.split('"')
# 奇数索引的部分是双引号包裹的内容,替换其中的换行/回车为空格
for i in range(1, len(parts), 2):
    # 把换行、回车替换为空格,再合并多余空格
    parts[i] = ' '.join(parts[i].replace('\r', '').replace('\n', ' ').split())
# 拼接回完整内容
fixed_content = '"'.join(parts)
print(fixed_content)
# 要写入文件可取消注释下面代码
# with open('output.txt', 'w', encoding='utf-8') as f:
#     f.write(fixed_content)

这个实现逻辑和你给出的awk命令完全对齐,运行后就能得到符合预期的输出,性能和可读性都比原逻辑更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 04:24:03