User:Eleanorg/Thematic1.1/Get Ship Position 2 - Regex

From XPUB & Lens-Based wiki
< User:Eleanorg
Revision as of 17:42, 1 December 2011 by Eleanorg (talk | contribs) (Created page with "Grabs ship's latitude and longitude position, and prints the longitude. <source lang=python> #!/usr/bin/env python #-*- coding:utf-8 -*- # grabs the most up-to-date lat & long ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Grabs ship's latitude and longitude position, and prints the longitude.

#!/usr/bin/env python
#-*- coding:utf-8 -*-

# grabs the most up-to-date lat & long using a regex, then prints the longitude

import urllib2, re

page = urllib2.urlopen("http://www.marinetraffic.com/ais/shipdetails.aspx?mmsi=235080274&header=true").read()

for m in re.findall(r"(\d+\.\d+) ?˚ ?/ ?(\d+\.\d+) ?˚", page):
    print m[1]
# matches in captured () are stored in a list; longitude is at index 1 (second item in list)

This version does the same, but assigns the longitude to a variable instead of printing it:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

# grabs the most up-to-date lat & long using a regex, then prints the longitude

import urllib2, re

page = urllib2.urlopen("http://www.marinetraffic.com/ais/shipdetails.aspx?mmsi=235080274&header=true").read()

for m in re.findall(r"(\d+\.\d+) ?˚ ?/ ?(\d+\.\d+) ?˚", page):
    longitude = m[1]