[英]Read a file in python from one particular word to another and put it in a list
所以假設我正在閱讀 Python 中的一個 txt 文件,它是這樣的:
.. 關鍵字- key1; 鍵2,鍵3; key4 摘要...
現在我想解析文件,直到找到單詞“Keywords”,然后將所有關鍵字放入一個列表中,所以列表應該如下所示:[“key1”,“key2”,“key3”,“key4 "]
因此,它基本上可以用逗號 (,) 或分號 (;) 或兩者的組合來分隔單詞 Abstract 和關鍵字之前的所有內容。
我如何 go 關於這個問題?
這是使用正則表達式的一種方法
import re
input_str = "this is a test Keywords- key1; key2, key3; key4 Abstract other stuff here"
p = re.compile(r'Keywords- (.+?)Abstract')
output = [v.strip() for v in re.split(';|,', p.findall(input_str)[0])] if p.findall(input_str) else list()
如果沒有匹配項,這將返回一個空列表或一個帶有空白修剪的匹配項列表。 所以在這個例子中,返回列表將是:
['key1', 'key2', 'key3', 'key4']
我使用re.split
因為它支持在多個分隔符上拆分,所以如果您有其他分隔符,您可以將它們添加到進一步的 pipe 分隔選項中。
這是另一個正則表達式版本。 與沒有列表理解的史蒂夫相同。
import re
s = '''Keywords- key1; key2, key3; key4 Abstract stuff
some of other text Keywords- key1; key2, key3; key4 Abstract
Keywords- key1; key2, key3; key4 Abstract
Keywords- key1; key2, key3; key4 Abstract'''
extract = r'Keywords-\s(.*)\sAbstract'
keywordList = re.findall(extract,s)
reg = r'\w+'
keywords = []
for i in range(len(keywordList)):
keywords += re.findall(reg, keywordList[i])
print(keywords)
# ['key1', 'key2', 'key3', 'key4', 'key1', 'key2', 'key3', 'key4', 'key1', 'key2', 'key3', 'key4', 'key1', 'key2', 'key3', 'key4']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.