apples723
Posts: 80
Joined: Sat Jun 22, 2013 3:13 pm

Weather in SVG

Mon Jul 22, 2013 4:59 pm

ok so i wrote another weather application this time it displays the weahter as a gui my only problem is when i want to change the location you have to change the lattitude and longitude manually i have tried using a module to convert it using the city location but when every i use any varabiles in the link it fails to pick it up take a look at my current code ill have some notes in it to see if you can help me

Code: Select all

import time
import urllib2, time
from xml.dom import minidom
import datetime
import codecs
import webbrowser
import easygui as eg
import Tkinter

#title = "Start"
#msg = "Touch Ok to begin"
#eg.msgbox(msg, title)
weather_xml = urllib2.urlopen('http://graphical.weather.gov/xml/SOAP_server/ndfdSOAPclientByDay.php?whichClient=NDFDgenByDay&lat=42.0228&lon=-93.4522&format=24+hourly&numDays=4&Unit=e').read() #if i try and define the lat and lon with string formating it wil fail i dont know why 
dom = minidom.parseString(weather_xml)


xml_temperatures = dom.getElementsByTagName('temperature')
highs = [None]*4
lows = [None]*4
for item in xml_temperatures:
    if item.getAttribute('type') == 'maximum':
        values = item.getElementsByTagName('value')
        for i in range(len(values)):
            highs[i] = int(values[i].firstChild.nodeValue)
    if item.getAttribute('type') == 'minimum':
        values = item.getElementsByTagName('value')
        for i in range(len(values)):
            lows[i] = int(values[i].firstChild.nodeValue)

xml_icons = dom.getElementsByTagName('icon-link')
icons = [None]*4
for i in range(len(xml_icons)):
    icons[i] = xml_icons[i].firstChild.nodeValue.split('/')[-1].split('.')[0].rstrip('0123456789')

xml_day_one = dom.getElementsByTagName('start-valid-time')[0].firstChild.nodeValue[0:10]
day_one = datetime.datetime.strptime(xml_day_one, '%Y-%m-%d')




output = codecs.open('weather-script-preprocess.svg', 'r', encoding='utf-8').read()

output = output.replace('ICON_ONE',icons[0]).replace('ICON_TWO',icons[1]).replace('ICON_THREE',icons[2]).replace('ICON_FOUR',icons[3])
output = output.replace('HIGH_ONE',str(highs[0])).replace('HIGH_TWO',str(highs[1])).replace('HIGH_THREE',str(highs[2])).replace('HIGH_FOUR',str(highs[3]))
output = output.replace('LOW_ONE',str(lows[0])).replace('LOW_TWO',str(lows[1])).replace('LOW_THREE',str(lows[2])).replace('LOW_FOUR',str(lows[3]))

one_day = datetime.timedelta(days=1)
days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
output = output.replace('DAY_THREE',days_of_week[(day_one + 2*one_day).weekday()]).replace('DAY_FOUR',days_of_week[(day_one + 3*one_day).weekday()])

codecs.open('weather-script-output.svg', 'w', encoding='utf-8').write(output)
#eg.msgbox("Working")
from subprocess import call
call(["inkscape.exe", "weather-script-output.svg", "--export-png=file.gif.png" ])
title = 'Done'
msg = 'Press Ok to get weather'
eg.msgbox(msg, title)

from PIL import Image, ImageTk
from Tkinter import Tk, Label, BOTH
from ttk import Frame, Style
from Tkinter import *
import Image
import PIL
filename = "file.gif.png"
basewidth = 300
img = Image.open(filename)
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
img.save('resize.jpg')
import urllib2
import json

request = urllib2.urlopen("http://api.aerisapi.com/observations/Nevada,IA?client_id=QD2ToJ2o7MKAX47vrBcsC&client_secret=0968kxX4DWybMkA9GksQREwBlBlC4njZw9jQNqdO")
response = request.read().decode("utf-8")
json = json.loads(response)
ob = json['response']['ob']
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
    def update_timeText():
        current = time.strftime("%H:%M:%S")
        timeText.configure(text=current)
        root.after(1000, update_timeText)
    
    def initUI(self):
          
        self.parent.title("Weather")
        self.pack(fill=BOTH, expand=1)
        
        Style().configure("TFrame", background="#333")
        bard = Image.open("resize.jpg")
        bardejov = ImageTk.PhotoImage(bard)
        label1 = Label(self, image=bardejov)
        if ob['tempF'] >= '80':
            label2 = Label(self, text="The current temp in Nevada is %r" % (ob['tempF']), bg="white")
        if ob['tempF'] <= '90':
            label2 = Label(self, text="With the heat index the temp in Nevada is %r" % (ob['heatindexF']), bg="white")
        #label3 = Label(self, text=if ob(['tempF']) =<90
        label1.image = bardejov
        label1.place(x=0, y=0)
        label2.place(x=20, y=196)
        


def main():
  
    root = Tk()
    root.geometry("295x400")
    app = Example(root)
    root.mainloop()  
    
    


if __name__ == '__main__':
    main()




apples723
Posts: 80
Joined: Sat Jun 22, 2013 3:13 pm

Re: Weather in SVG

Mon Jul 29, 2013 4:37 pm

bump

ajbarnes
Posts: 26
Joined: Tue Sep 11, 2012 9:24 pm

Re: Weather in SVG

Tue Jul 30, 2013 10:18 pm

Hi,

What error were you getting, and what values were you trying to insert. Thanks.

DrMag
Posts: 63
Joined: Sat Jun 01, 2013 7:59 pm

Re: Weather in SVG

Wed Jul 31, 2013 7:02 pm

Agreed; more information on the errors you're encountering would be helpful. For example-- you mention that putting the lat/long in by string formatting isn't working. Where is it failing? Does the formatting itself fail, or does it format to a string that fails when you try to pull the results?

I'd expect the latter, in which case something like

Code: Select all

weather_xml=urllib2.urlopen('...&lat={0:.4f}&lon={1:.4f}...'.format(latitude,longitude))
is probably what you're looking for. Just plugging in the float values would insert more decimal places than the xml script may be looking for. But I'm just guessing at the problem here... some description of your actual error results would be helpful.

Return to “Python”