是否可以從字串中取出一對括號中的文本到一個串列中,將非括號文本放在另一個串列中,兩個串列都嵌套在同一個串列中?這就是我的意思:
"hello{ok}why{uhh}so"-->[["hello","why","so"],["ok","uhh"]]
uj5u.com熱心網友回復:
re根據您共享的示例,使用模塊非常容易。但是,如果您的文本很大,您將不得不考慮即興發揮這個解決方案。使用 re,您可以執行以下操作
import re
raw_text = "hello{ok}why{uhh}so"
result = [re.split(r"{[A-Za-z]*}", raw_text),re.findall(r"{([A-Za-z]*)}",raw_text)]
print(result)
產生結果
[['hello', 'why', 'so'], ['ok', 'uhh']]
uj5u.com熱心網友回復:
以下代碼可能會對您有所幫助
input_str = "hello{ok}why{uhh}so"
list1, parsed_parentheses = [], []
for index in range(len(input_str)):
if input_str[index] == "{":
parsed_parentheses.append(input_str[index])
substr = ""
continue
else:
if parsed_parentheses == []:
continue
if input_str[index] == "}":
parsed_parentheses.append(input_str[index])
list1.append(substr)
if "{" == parsed_parentheses[-1]:
substr = input_str[index]
input_str = input_str.replace("{", "-").replace('}', "-").split('-')
list2 = list(set(input_str) - set(list1))
result = [list2, list1]
它產生以下結果
[['hello', 'why', 'so'], ['ok', 'uhh']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/435685.html
上一篇:如何使用模式從字串中獲取特定資料
