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

Python读取文件时匹配到指定单词后打印换行分隔的问题如何解决

问题根因

你当前的代码在检测到行包含location时,会先执行打印换行的逻辑,再输出该行本身,所以换行就出现在了location的前面。

调整后代码

with open('test.txt') as my_file:
    match = False
    for line in my_file:
        current_content = " ".join(line.split())
        # 先处理匹配区间逻辑和行输出
        if 'text1' in line:
            match = True
            print(current_content)
        elif 'text3' in line:
            match = False
            print(current_content)
        elif match:
            print(current_content)
            # 输出完当前行后判断是否是location行,是的话追加换行
            if 'location' in line:
                print('\n')

改动说明

  • 调换了location判断和行输出的顺序,确保换行打在location行的后面
  • 统一处理行内容的空格格式化,避免重复写split和join逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:36:07