4 回答

TA貢獻(xiàn)1840條經(jīng)驗(yàn) 獲得超5個(gè)贊
re.DOTALL您可以使用正則表達(dá)式來(lái).匹配任何字符,包括換行符。一旦在兩個(gè)分隔符之間有了文本,就可以使用另一個(gè)不帶 的正則表達(dá)式來(lái)re.DOTALL提取至少包含一個(gè)非空白字符 ( \S) 的行。
import re
lst = []
with open('input.txt') as f:
text = f.read()
match = re.search('This is a fairy tale written by(.*?)This story is awesome',
text, re.DOTALL)
if match:
lst.extend(re.findall('.*\S.*', match.group(1)))
print(lst)
給出:
[' John Doe and Mary Smith', ' Auckland,somewhere']

TA貢獻(xiàn)1808條經(jīng)驗(yàn) 獲得超4個(gè)贊
你可以從這個(gè)開(kāi)始:
re.search(r'(?<=This is a fairy tale written by\n).*?(?=\n\s*This story is awesome)', s, re.MULTILINE|re.DOTALL).group(0)
并微調(diào)這個(gè)正則表達(dá)式。re.MULTILINE
可能會(huì)被省略,因?yàn)槟銢](méi)有^
或$
無(wú)論如何,但也re.DOTALL
需要讓.
匹配換行符。上面的正則表達(dá)式使用向前看和向后看(?<=)
,(?=)
。如果您不喜歡那樣,您可以使用括號(hào)來(lái)代替捕獲。

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
如果您可以從文檔文件創(chuàng)建字符串列表,則無(wú)需使用正則表達(dá)式。只需執(zhí)行這個(gè)簡(jiǎn)單的程序:
fileContent = ['This is a fairy tale written by','John Doe and Mary Smith','Auckland,somewhere','This story is awesome',
'Some other things', 'story texts', 'Not Important data',
'This is a fairy tale written by','Kem Cho?','Majama?','This story is awesome', 'Not important data']
authorsList = []
for i in range(len(fileContent)-3):
if fileContent[i] == 'This is a fairy tale written by' and fileContent[i+3] == 'This story is awesome':
authorsList.append([fileContent[i+1], fileContent[i+2]])
print(authorsList)
在這里,我只是檢查'This is a fairy tale written by'and'This story is awesome'如果找到,則在列表中在它之間添加文本。
輸出:
[['John Doe and Mary Smith', 'Auckland,somewhere'], ['Kem Cho?', 'Majama?']]

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超11個(gè)贊
嘗試改用它。它應(yīng)該匹配這兩個(gè)字符串之間的任何內(nèi)容。
re.search(r'(?<=This is a fairy tale).*?(?=This story is awesome)',text)
添加回答
舉報(bào)