使用多个分隔符/条件拆分列表的字符串元素。有好的Python库吗?

2024-06-02 12:00:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,我一直在使用Google refinehttp://code.google.com/p/google-refine/和Excel来清理一个混乱的数据库,但是,我认为只要我能够得到一些可以重用的‘配方’,Python可以做得更好。在

我的问题的一个变化是数据库的“位置”字段不一致。大约95%的数据的格式在list 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]

Tags: of数据in数据库forgoogle配方excel
1条回答
网友
1楼 · 发布于 2024-06-02 12:00:42

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

#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

输出:

^{pr2}$

相关问题 更多 >