我是 Python 的新手,我一直在使用 Google refine http://code.google.com/p/google-refine/ 的组合来清理一个困惑的数据库。和 Excel,但是,我认为 Python 可以做得更好,只要我能够获得一些可以重用的“食谱”。
我的问题的一个变体是数据库的“位置”字段不一致。大约 95% 的数据具有列表 Location1 中的格式,我已经能够以比使用 Excel 过滤器更有效的方式使用 python 进行处理。但是,我正在寻找一个 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']]
