拆分多个单词或短划线

时间:2014-03-23 18:25:34

标签: python regex

我试图将字符串拆分成多个字符串。我正在使用re库但遇到了问题。说我的字符串是" " Yakima,WA [4660,12051] 49826"如果我这样做,我会工作的:

>>> import re
>>> x = "Yakima, WA[4660,12051]49826"
>>> re.split('\W+', x)

它将返回

['Yakima', 'WA', '4660', '12051', '49826']

我希望它。但我遇到的问题是,如果城市中有一个( - )或一个空间,那么如何才能将城市保持在一起。我将与多个城市打交道,有些城市有2到3个工作城市,有些城市有破折号。我需要保留3个数据结构,包括城市和州的组合,坐标和人口。

>>> x = "Winston-Salem, NC[3610,8025]131885"
>>> re.split('\W+', x)
['Winston', 'Salem', 'NC', '3610', '8025', '131885']

>>> x = "West Palm Beach, FL[2672,8005]63305"
>>> re.split('\W+', x)
['West', 'Palm', 'Beach', 'FL', '2672', '8005', '63305']

我希望:

['Winston-Salem', 'NC', '3610', '8025', '131885']
['West Palm Beach', 'FL', '2672', '8005', '63305']

2 个答案:

答案 0 :(得分:6)

您可以按[^\w\s-]+分组:

>>> x = "Winston-Salem, NC[3610,8025]131885"
>>> re.split('[^\w\s-]+', x)
['Winston-Salem', ' NC', '3610', '8025', '131885']

>>> x = "West Palm Beach, FL[2672,8005]63305"
>>> re.split('[^\w\s-]+', x)
['West Palm Beach', ' FL', '2672', '8005', '63305']

[^\w\s-]+基本上不是指字母数字(a-zA-Z0-9_),不是空白字符而不是-

答案 1 :(得分:3)

您可以尝试按,[]进行拆分:

re.split('[,\[\]]', x)

<强>演示:

import re

L = ["Yakima, WA[4660,12051]49826",
"Winston-Salem, NC[3610,8025]131885",
"West Palm Beach, FL[2672,8005]63305"]

for e in L:
    print re.split('[,\[\]]', e)

>>> ['Yakima', ' WA', '4660', '12051', '49826']
>>> ['Winston-Salem', ' NC', '3610', '8025', '131885']
>>> ['West Palm Beach', ' FL', '2672', '8005', '63305']