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

Python 2.7读取多行文本文件:如何按段输出内容求助

解决Python提取PD:EOL分隔段落的问题

Hey there! Let's sort out this problem step by step.

First, let's break down the issues with your original code:

  • Syntax errors: You missed a colon after with open('test.txt','r') as f, and the for loop isn't properly indented under the with block. Also, in Python 3, print requires parentheses (like print(line)).
  • Logic flaw: Using break right after printing when you find 'CZ' stops the loop immediately, so you only get the first snippet of the line instead of the full segment up to the first PD:EOL.

Your goal is to extract the first segment ending with PD:EOL from your test.txt content. Since all the content is in a single line, we don't need to loop through lines—we can just read the whole content and process it directly.

Here are two simple, working solutions:

Method 1: Split content by the delimiter

with open('test.txt', 'r') as f:
    content = f.read().strip()  # Read the entire file and trim extra spaces at the ends

# Split using 'PD:EOL ' as the separator, take the first part, then add the delimiter back
first_segment = content.split('PD:EOL ')[0] + 'PD:EOL '
print(first_segment)

Method 2: Locate the delimiter and slice the string

with open('test.txt', 'r') as f:
    content = f.read().strip()

# Find the position of the first 'PD:EOL ' and calculate the end of the target segment
delimiter = 'PD:EOL '
end_index = content.find(delimiter) + len(delimiter)
first_segment = content[:end_index]
print(first_segment)

Both methods will output exactly what you need:

CZ:xxx CZ:yyy CZ:zzz PD:EOL

The key here is recognizing your file content is a single line, so reading the whole thing at once makes processing much simpler than looping line by line.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:54:27