簡體   English   中英

python在文本中的兩點之間替換單詞

[英]python substitute words between two points in a text

在過去的幾天中,我正在處理正則表達式。 所以,假設我有一段文字

text = '
1. sometext sometext sometext given as follows:
«book one
title here
part one
1. mpla mpla mpla
2. some text some text «here spesific text»
book two 
1. some text some text.
2. «also» try this in case of emergency.»

book three
part three
directions to home'

並且我正在嘗試查找“«”和“»”之間的所有圖書。 用“章節”一詞進行更改,然后將其取回。 通過使用正則表達式,我無法獲得想要的結果,因為據我所知,正則表達式並不是計算到目前為止已傳遞的“»”的最佳解決方案。

例如,如果我使用

print re.findall(r'«([book\s\S+]*?)»', data, re.DOTALL)

我只會收到第一個“»”之前的文本。 有沒有辦法獲得第一本書和第二本書?

我也試過這個:

print re.findall(r'(?<=«)(?=(book\s\S+))|(?=[^«]*»)(?=(book\s\S+))',data, re.DOTALL)

但都行不通。 有沒有一種獲取結果的方法,或者我應該使用除正則表達式之外的其他方法?

一種解決方案是分兩部分進行此操作,如下所示:

print re.findall(r"(book\s\S+)", re.search("«(.*)»", text, re.S).group(1), re.S)

這首先找到外部« » ,然后在內部搜索書籍。

這給出以下輸出:

['book one', 'book two']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM