2016-01-27 94 views
0

如何從Python中的URL中提取座標(Lat,Long),我有點遺憾。如何從Python中的URL中提取座標(lat,lan)?

總是我recive這樣的網址:

https://www.testweb.com/cordi?ll=41.403781,2.1896&z=17&pll=41.403781,2.1896 

哪裏需要提取第二組此URL(在這種情況下:41.403781,2.1896)只是說,這並不總是第一而第二組座標將是相同的。

我知道,這可以用一些正則表達式來完成,但我對它不夠好。

+0

肯定有一個體面的URL解析爲Python在那裏? – Biffen

+0

它總是出現在URL的最後?因爲如果是這種情況,那麼'[\ d。,] + $'將會完成這項工作。 [Demo](https://regex101.com/r/rB7mF9/2) –

+0

謝謝Biffen,我會看看是否存在一些東西。是的@noob這是總是模式。 – Shudy

回答

1

下面介紹如何使用正則表達式做到這一點:

import re 
m = re.search(r'pll=(\d+\.\d+),(\d+\.\d+)', 'https://www.testweb.com/cordi?ll=41.403781,2.1896&z=17&pll=41.403781,2.1896') 
print m.groups() 

結果:('41.403781', '2.1896')

你可能想看看模塊urlparse一個更強大的解決方案。

+0

謝謝!它工作完美! – Shudy

1

有裏urlparse一個功能「裏urlparse」和「parse_qs」可靠地訪問這些數據,如下圖所示

$ python 
Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> u="""https://www.testweb.com/cordi?ll=41.403781,2.1896&z=17&pll=41.403781,2.1896""" 
>>> import urlparse 
>>> x=urlparse.urlparse(u) 
>>> x 
ParseResult(scheme='https', netloc='www.testweb.com', path='/cordi', params='', query='ll=41.403781,2.1896&z=17&pll=41.403781,2.1896', fragment='') 
>>> x.query 
'll=41.403781,2.1896&z=17&pll=41.403781,2.1896' 
>>> urlparse.parse_qs(x.query) 
{'ll': ['41.403781,2.1896'], 'z': ['17'], 'pll': ['41.403781,2.1896']} 
>>> 
+0

謝謝!我會看一看 – Shudy

相關問題