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 theforloop isn't properly indented under thewithblock. Also, in Python 3,printrequires parentheses (likeprint(line)). - Logic flaw: Using
breakright 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 firstPD: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
相关产品推荐
相关产品推荐

