如何修改Python代码实现从criteria_1打印字符串至criteria_2?
解决从指定标识打印到终止标识的Python代码问题
Hey there! Let's get this sorted so you can print text starting from criteria_1 and stopping at criteria_2 correctly. Your current code has a couple of hiccups (like print(words + 1) which won't work—words is a list, adding an integer will throw an error), so here's how to fix it up:
完整修改后的代码(状态跟踪法)
这是最灵活的写法,能处理标识重复出现的情况:
criteria_1 = "x" # 记得给标识加引号,假设它们是字符串 criteria_2 = "y" raw = parser.from_file(MIPR_File_Path) info = raw['content'] words = info.split() # 用一个变量标记是否处于打印状态 is_printing = False for word in words: # 遇到起始标识,开启打印模式 if word == criteria_1: is_printing = True # 要是想把criteria_1本身也打印出来,就解开下面这行注释 # print(word) continue # 遇到终止标识,关闭打印模式 if word == criteria_2: is_printing = False # 同理,想打印criteria_2的话就解开这行 # print(word) continue # 只有在打印模式开启时,才输出当前单词 if is_printing: print(word)
关键逻辑说明
- 我们用
is_printing这个布尔变量来跟踪是否需要打印当前内容:- 碰到
criteria_1时,切换到打印状态;碰到criteria_2时,切换回非打印状态 - 可以自由选择是否包含起始/终止标识本身(只需要注释/解开对应的
print行就行) - 这种写法能处理文本中多次出现
criteria_1或criteria_2的场景
- 碰到
备选写法(索引定位法)
如果你确定criteria_1和criteria_2在文本中各只出现一次,可以用索引直接定位后切片打印:
criteria_1 = "x" criteria_2 = "y" raw = parser.from_file(MIPR_File_Path) info = raw['content'] words = info.split() try: # 找到起始标识的位置 start_pos = words.index(criteria_1) # 从起始标识之后的位置找终止标识 end_pos = words.index(criteria_2, start_pos + 1) # 打印两个标识之间的内容(调整切片来决定是否包含端点) # 不包含起始和终止:words[start_pos+1 : end_pos] # 包含起始和终止:words[start_pos : end_pos+1] for word in words[start_pos+1 : end_pos]: print(word) except ValueError: # 处理找不到任一标识的情况 print("Error: Could not find either criteria_1 or criteria_2 in the content")
这种写法更简洁,但如果标识重复出现或者不存在,需要用try-except来捕获异常。
内容的提问来源于stack exchange,提问作者Pierce Deamer
相关产品推荐
相关产品推荐

