rolando2424 Posted May 12, 2008 at 06:29 PM Report Share #184724 Posted May 12, 2008 at 06:29 PM Este pequeno script que fiz agora serve para ir ao site do instituto de meteorologia (http://www.meteo.pt/) e ir ver qual é o estado do tempo e a temperatura máxima e mínina no Porto (porque é onde moro e não tive pachorra para fazer para as outras cidades, depois eu trato disso) EDIT: Já está a dar para várias cidades, só têm que ir à variável patt e no temp["Porto"] colocar lá o nome da cidade que querem saber a informação (consultem a variável temp). Depois faço uma interface para isto. #!usr/bin/env python # -*- coding: iso-8859-15 -*- import urllib import re import pdb ## TODO: Search cities with only one word (for example, "Viana" should find "Viana do Castelo") ## Create an update_cache method (maybe call it once every hour and then delete the file ## when with the __del__ method?) class Client: """Connects to the Portuguese weather institute to see the weather conditions and the temperature of several Portuguese cities. Check what cities you can search in the following web page: http://www.meteo.pt/pt/html.jsp """ def __init__(self): ## TODO: Check if the computer is connected to the internet try: self.page = urllib.urlopen("http://www.meteo.pt/pt/html.jsp") except IOError: print "There isn't a connection to the internet" # No connection to teh tubes # Format the content of the web page tmp_content = self.page.readlines() self.content = [] saving = 0 # The page is divided into 2 tables, so we only start # saving things when this reaches 2 for line in tmp_content: line = line.replace("\n", "").replace("\r", "") if saving == 2: self.content.append(line) if "tablelist_wid" in line: saving += 1 else: pass self.content = "\n".join(self.content) # Cities not working: braganca, evora # Cities removed from the web page: angra do heroismo, santarem, guarda # braga, # New cities: Evora, Flores, Ponta Delgada, Porto Santo, # Viana do Castelo, Vila Real, Viseu self.known_cities= ( "beja", "braganca", "cabo carvoeiro", "castelo branco", "coimbra", "evora", "faro", "flores", "funchal", "horta", "lisboa", "ponta delgada", "penhas douradas", "portalegre", "porto", "porto santo", "sagres", "sines", "viana do castelo", "viana castelo", "vila real", "viseu" # "bragança", "évora" ) # This will be used in the future, ignore it for now (it does nothing) self.city_convertion = { "braganca":"bragança", "evora":"évora", ## TODO: Finish this thing } self.pattern = re.compile(r""" # The .*? at the end of the lines is so remove the \t # characters that appear in the page source <tr\ class="tablelist_bg[01]">.*? # Start of a city's information <td> (.*?) </td>.*? # Name of the city <td\ align="center"> (.*?) </td>.*? # Weather Status <td\ align="center"> (.*?) </td>.*? # Temperature <td\ align="center"> (.*?) </td>.*? # Velocity of the wind <td\ align="center"> (.*?) </td>.*? # Direction of the wind <td\ align="center"> (.*?) </td>.*? # Humidity (percentage) <td\ align="center"> (.*?) </td>.*? # Precipitation (mm) <td\ align="center"> (.*?) </td>.*? # Pressure (hPa) <td\ align="center"> (.*?) </td>.*? # Mist (percentage) <td\ align="center"> (.*?) </td> # Snow (cm) """, re.DOTALL | re.VERBOSE) def search_city(self, city_name): """Search the web page source code and retrieve the information that exists for the city "city_name" Returns a tuple with the information in the following order: ( Name of the city, Weather, Temperature (ºC), Speed of the wind (km/h), Direction of the wind (cardinal points), Humidity in the air (%), Precipitation (mm), Pressure (hPa), Mist in the air (%), Snow on the ground (cm) ) If the web page doesn't have some the information for the city, that stat will get the value of "---" """ city_name = city_name.capitalize() if city_name == "Viana do castelo": # Workaround (city is called Viana # Castelo in the web page) city_name = "Viana" results = re.findall(self.pattern, self.content) for line in results: line = list(line) # re.findall return a list of tuples, so we # need to convert the tuple to a list so we can # make some changes into it line[0] = line[0].split("(")[0].strip() # Remove adicional stuff from the name line[0] = line[0].capitalize() # So it stays the same as the city_name # These two cities have a similar name, so we need to workaround them if city_name == "Porto" and city_name == line[0]: return line elif city_name == "Porto santo" and city_name in line[0]: return line elif city_name in line[0]: return line def get_information(self, city): """Get information for the city from the web page's source. Returns a tuple with the information about the city in the following format: ( Name of the city, Weather, Temperature (ºC), Speed of the wind (km/h), Direction of the wind (cardinal points), Humidity in the air (%), Precipitation (mm), Pressure (hPa), Mist in the air (%), Snow on the ground (cm) ) If the web page doesn't have some the information for the city, that stat will get the value of "Informacao nao disponivel" Returns 1 if the city doesn't exist in the web page. """ if city.lower() not in self.known_cities: return 1 else: #pdb.set_trace() tmp_result = self.search_city(city) result = [] for info in tmp_result: if info == "---": result.append("Informacao nao disponivel") else: result.append(info) return tuple(result) if __name__ == "__main__": c = Client() (place, weather, temp, vel_wind, dir_wind, humidity, rain, pressure, mist, snow) = c.get_information("Porto") print "Estado do tempo:", weather print "Temperatura:", temp Exemplo de uso: rolando@main-computer:~/Desktop$ python meteo.py Porto: Aguaceiros Temperatura minima: 19 Temperatura maxima: 12 rolando@main-computer:~/Desktop$ EDIT @ Skin : Geshied correctly EDIT2: Actualizei o código, mas para obterem as novas versões do código, se calhar é melhor irem ao site onde está o bot de IRC do Tharis, pois este código passou a fazer parte desse projecto. Link (syntax highlight): http://code.google.com/p/ircbot-in-python/source/browse/trunk/meteo.py Link (plain text): http://ircbot-in-python.googlecode.com/svn/trunk/meteo.py Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄 Link to comment Share on other sites More sharing options...
magician Posted May 12, 2008 at 06:35 PM Report Share #184728 Posted May 12, 2008 at 06:35 PM Eu já pensei eu fazer algo parecido alias ainda comecei mas depois parei por falta de tempo, no meu caso seria um site internacional de meteorologia que é muito usado a nível de agricultora a muito certo e depois de processados os dados era enviada uma sms para determinados números de telemóveis coma a previsão do tempo. Era algo para trabalhar como servidor e enviaria previsão tipo 3 vezes ao dia. I haven’t lost my mind; it’s backed up on DVD somewhere! Link to comment Share on other sites More sharing options...
rolando2424 Posted May 12, 2008 at 06:56 PM Author Report Share #184732 Posted May 12, 2008 at 06:56 PM Eu já pensei eu fazer algo parecido alias ainda comecei mas depois parei por falta de tempo, no meu caso seria um site internacional de meteorologia que é muito usado a nível de agricultora a muito certo e depois de processados os dados era enviada uma sms para determinados números de telemóveis coma a previsão do tempo. Era algo para trabalhar como servidor e enviaria previsão tipo 3 vezes ao dia. Eu por acaso também tenho um pequeno alias (e um pequeno script) de bash que utiliza um programa chamado "metar" que se liga a uma base de temperaturas internacionais para ir buscar as temperaturas no Porto. alias metar_portugal="metar -d lppr" # Porto, Pedras Rubras function temp() { metar -d lppr | echo -ne "A temperatura actual e: ${LIGHTRED}$(awk '/Temperature/ {print $3}') ${NC}graus.\n" } (O ${LIGHTRED} e o ${NC} são umas variáveis para ser mais fácil mudar a cor) Para usar é só: rolando@main-computer:~$ metar_portugal LPPR 121830Z 23007KT 190V270 9999 BKN012 15/13 Q1015 Station : LPPR Day : 12 Time : 18:30 UTC Wind direction: 230 (SW) Wind speed : 7 KT Wind gust : 7 KT Visibility : 9999 M Temperature : 15 C Dewpoint : 13 C Pressure : 1015 hPa Clouds : BKN at 12900 ft Phenomena : rolando@main-computer:~$ temp A temperatura actual é: 15 graus. Eu só fiz o script em Python porque já era algo que vinha com intenções de fazer desde à já algum tempo. Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄 Link to comment Share on other sites More sharing options...
MacgyverPT Posted June 12, 2008 at 07:27 PM Report Share #190948 Posted June 12, 2008 at 07:27 PM rolando2424, no primeiro scipt (usando o python), na ultima parte onde dizes as temperaturas não terás trocado as frases, ou as temperaturas? Tu tens isto: print print result[0] print "Temperatura minima:", result[1] print "Temperatura maxima:", result[2] print Eu alterei o "Porto" para "Beja", e ao executar aparece: Beja: Céu pouco nubladoTemperatura minima: 32 Temperatura maxima: 18 A temp. Máxima não terá trocada com a Mínima? Link to comment Share on other sites More sharing options...
rolando2424 Posted June 12, 2008 at 11:08 PM Author Report Share #191004 Posted June 12, 2008 at 11:08 PM Sim, está trocado. Na versão nova que tenho aqui feita já está direito. Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄 Link to comment Share on other sites More sharing options...
rolando2424 Posted July 26, 2008 at 03:24 AM Author Report Share #201371 Posted July 26, 2008 at 03:24 AM Bem, é melhor actualizar isto com a dita "versão nova". Acontece que o fnds teve a grande ideia de incorporar este sistema no bot de IRC que o Tharis está a fazer, por isso seria melhor passarem a ir buscar o código novo ao site do bot: Com syntax highlight: http://code.google.com/p/ircbot-in-python/source/browse/trunk/meteo.py Plain text: http://ircbot-in-python.googlecode.com/svn/trunk/meteo.py E é melhor actualizarem para esta versão, porque o site do instituto de meteorologia mudou o design, e o script inicial já não funciona. Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄 Link to comment Share on other sites More sharing options...
joaoqalves Posted July 26, 2008 at 12:52 PM Report Share #201412 Posted July 26, 2008 at 12:52 PM Bem, é melhor actualizar isto com a dita "versão nova". Acontece que o fnds teve a grande ideia de incorporar este sistema no bot de IRC que o Tharis está a fazer, por isso seria melhor passarem a ir buscar o código novo ao site do bot: Com syntax highlight: http://code.google.com/p/ircbot-in-python/source/browse/trunk/meteo.py Plain text: http://ircbot-in-python.googlecode.com/svn/trunk/meteo.py E é melhor actualizarem para esta versão, porque o site do instituto de meteorologia mudou o design, e o script inicial já não funciona. E mudou para um design mais fixe 😛 Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!Queres estar na moda? Utiliza a pesquisa e evita criar um tópico desnecessário. Link to comment Share on other sites More sharing options...
rolando2424 Posted July 26, 2008 at 08:10 PM Author Report Share #201449 Posted July 26, 2008 at 08:10 PM E mudou para um design mais fixe 😄 Eu até me assustei quando vi a página inicial em Flash 😛 Não me responsabilizo por qualquer dano ocorrido no seguimento dos meus conselhos. Prontos, a minha pessoa está oficialmente protegida legalmente 😄 Link to comment Share on other sites More sharing options...
hmiguel Posted December 7, 2008 at 06:10 AM Report Share #230907 Posted December 7, 2008 at 06:10 AM Vinha aqui a passear....vi o código....pera lá...eu tb já andei nas meteorologias....e fui ao sotão... ? #!/usr/bin/env python # -*- coding: utf-8 -*- import urllib city = (raw_input("Cidade: ")) code = urllib.urlopen("http://www.meteo.pt/pt/html.jsp").readlines() op = ["\nLocal:","Estado:","Temp. (ºC):","Vento (vel.):","Vento (dir.):","Humid. (%):", "Prec. (mm):","Press (hPa):","Neb. (%):", "Neve (cm):"] for i in range(300,len(code)): if city.lower() in code[i].lower(): for j in range(0,10): print op[j],code[i+j][code[i+j].find(">")+1:code[i+j].find("</")] É um codigo muito simples....como podem ver n tem quaisquer proteccoes, nem "power search"...mas faz o serviço.... 😛 É o meu primeiro post aqui no PAP....e espero que não seja o ultimo.... 😛 Cumps "Homem que é Homem não usa Java!" Link to comment Share on other sites More sharing options...
fnds Posted December 7, 2008 at 12:07 PM Report Share #230923 Posted December 7, 2008 at 12:07 PM Bem vindo 😛 Link to comment Share on other sites More sharing options...
djthyrax Posted December 7, 2008 at 01:49 PM Report Share #230940 Posted December 7, 2008 at 01:49 PM Bem vindo Hugo. 😛 Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum! Link to comment Share on other sites More sharing options...
eduardo carvalho Posted December 25, 2008 at 05:33 PM Report Share #234129 Posted December 25, 2008 at 05:33 PM e esse codigo para vb.net ninguem arranja ? Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now