使用多个分隔符/条件拆分列表的字符串元素.任何好的Python库



我是Python的新手,我一直在使用Google refine组合清理一个混乱的数据库http://code.google.com/p/google-refine/然而,我认为Python可以做得更好,只要我能得到一些可以重复使用的"食谱"。

我的问题的一个变体是数据库的"位置"字段不一致。大约95%的数据具有Location1列表中的格式,我能够用python以比使用Excel过滤器更有效的方式处理它。然而,我正在寻找一个python库或配方,它可以让我处理数据库中的所有类型的地理位置,也许可以在列表中定义模式。

提前感谢您的帮助!

Location1=['Washington, DC','Miami, FL','New York, NY']
Location2=['Kaslo/Nelson area (Canada), BC','Plymouth (UK/England)', 'Mexico, DF - outskirts-, (Mexico),']
Location3=['38.206471, -111.165271']
# This works for about 95% of the data, basically US addresses on Location1 type of List
CityList=[loc.split(',',1)[0] for loc in Location1]
StateList=[loc.split(',',1)[1] for loc in Location1]

不确定您是否仍有问题,但我相信以下答案对您有效:

#location_regexes.py
import re
paren_pattern = re.compile(r"([^(]+, )?([^(]+?),? (([^)]+))")
def parse_city_state(locations_list):
    city_list = []
    state_list = []
    coordinate_pairs = []
    for location in locations_list:
        if '(' in location:
            r = re.match(paren_pattern, location)
            city_list.append(r.group(2))
            state_list.append(r.group(3))
        elif location[0].isdigit() or location[0] == '-':
            coordinate_pairs.append(location.split(', '))
        else:
            city_list.append(location.split(', ', 1)[0])
            state_list.append(location.split(', ', 1)[1])
    return city_list, state_list, coordinate_pairs
#to demonstrate output
if __name__ == "__main__":
    locations = ['Washington, DC', 'Miami, FL', 'New York, NY',
                'Kaslo/Nelson area (Canada), BC', 'Plymouth (UK/England)',
                'Mexico, DF - outskirts-, (Mexico),', '38.206471, -111.165271']
    for parse_group in parse_city_state(locations):
        print parse_group

输出:

$ python location_regexes.py 
['Washington', 'Miami', 'New York', 'Kaslo/Nelson area', 'Plymouth', 'DF - outskirts-']
['DC', 'FL', 'NY', 'Canada', 'UK/England', 'Mexico']
[['38.206471', '-111.165271']]

最新更新