簡體   English   中英

重復分割數字和字符串

[英]Splitting numbers and strings repeatedly

我有以下字符串:

s = index ( 1.0000000e+00 2.0000000e+00 3.0000000e+00)  _x_ ( error error error ) t ( 1.2500000e+02 1.2500000e+02 1.2500000e+02 ) 

我需要將其分為以下列表:

['index', '1.0000000e+00 2.0000000e+00 3.0000000e+00', 
'_x_', 'error error error',
't', '1.2500000e+02 1.2500000e+02 1.2500000e+02']

我無法為此提出一個正則表達式。

您可以使用以下正則表達式來拆分此字符串(最后一個列表的項目將是一個空字符串。):

    import re
    s = "index ( 1.0000000e+00 2.0000000e+00 3.0000000e+00)  _x_ ( error error error ) t ( 1.2500000e+02 1.2500000e+02 1.2500000e+02 ) "
    re.split("\s*?(?:\(|\))\s*", s)

結果是:

['index', '1.0000000e+00 2.0000000e+00 3.0000000e+00', '_x_', 'error error error', 't', '1.2500000e+02 1.2500000e+02 1.2500000e+02', '']

另外,您可以使用以下正則表達式提取字符串的組件,然后對其進行處理(例如,從子字符串中去除空格)。 此正則表達式假定字符串具有平衡的左/右括號:

re.findall("(?:(?<=\()[^)]*?(?=\))|[a-z_]+)",s)

它應該產生以下輸出:

['index', ' 1.0000000e+00 2.0000000e+00 3.0000000e+00', '_x_', ' error error error ', 't', ' 1.2500000e+02 1.2500000e+02 1.2500000e+02 ']

這是執行此操作的列表理解:

[item.strip() for item in s.replace("(", ")").split(")")]

這是一些基本可以滿足您需求的代碼。 幾乎。

mylist = []
for item in s.replace("(", ";").replace(")", ";").split(";"):
    mylist.append(item.strip())

print mylist[:-1]

輸出:

['index', '1.0000000e+00 2.0000000e+00 3.0000000e+00', '_x_', 'error error error', 't', '1.2500000e+02 1.2500000e+02 1.2500000e+02']

與@AlexKotliarov的答案類似,但只是在空格和parens上分開

>>> import re
>>> re.split(r'[\s()]+', s)

輸出:

['index', '1.0000000e+00', '2.0000000e+00', '3.0000000e+00', '_x_', 'error', 'error', 'error', 't', '1.2500000e+02', '1.2500000e+02', '1.2500000e+02', '']

說明:

在集合[ .. ]分割一個或多個字符+ :空格\\s和括號()

暫無
暫無

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

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