我正在開發一個 python 自動化腳本,我想根據正則表達式匹配提取特定段落,但我不知道如何提取該段落。以下是我的案例的示例:解決方案:(一致模式)我要提取的段落(不一致模式)遠程值:x(一致模式)以下是我目前正在制作的程序,如果有人能啟發我,那就太好了!import retest= 'Solution\s:'test1='Remote'with open('<filepath>', 'r') as extract: lines=extract.readlines() for line in lines: x = re.search(test, line) y = re.search(test1, line) if x is not y: f4.write(line) print('good') else: print('stop')
1 回答

慕桂英3389331
TA貢獻2036條經驗 獲得超8個贊
這可以使用正則表達式輕松完成,例如:
import re
text = r"""
Solution\s:
The paragraph I
want to extract
Remote
Some useless text here
Solution\s:
Another paragraph
I want to
extract
Remote
"""
m = re.findall(r"Solution\\s:(.*?)Remote", text, re.DOTALL | re.IGNORECASE)
print(m)
其中text表示一些感興趣的文本(例如,從文件中讀?。覀兿M麖闹刑崛∩诒J絊olution\s:和之間的所有部分Remote。在這里,我們使用 IGNORECASE 搜索,以便即使使用不同的大小寫拼寫,也可以識別哨兵模式。
上面的代碼輸出:
['\nThe paragraph I\nwant to extract\n', '\nAnother paragraph\nI want to\nextract\n']
請閱讀https://docs.python.org/3/library/re.html上的 Python re 庫文檔了解更多詳細信息。
添加回答
舉報
0/150
提交
取消