java天气实例

谷歌天气的api已经关闭,百度的在服务器访问不正常,显示无数据

中国天气网比较全面的天气情况接口已经更改,获得的不再是当天的天气

中国天气网比较简单的接口仍然可以用

http://www.weather.com.cn/data/sk/城市代码.html 
http://www.weather.com.cn/data/cityinfo/城市代码.html

中国天气网对应的天气城市代码

//http://pan.baidu.com/share/link?shareid=709379960&uk=705537436

本例子获得的是雅虎天气网的天气情况

http://weather.yahooapis.com/forecastrss?w=城市代码&u=c

城市代码查询: https://weather.yahoo.com/这里输入你想要查询的城市,网址的最后的数据就是城市的id

当然雅虎还有一个旧的天气接口

http://weather.yahooapis.com/forecastrss?p=旧城市代码&u=c

旧的城市代码都是以chxx开头.这里有一份比较详细的旧城市代码:

//http://pan.baidu.com/share/link?shareid=737990724&uk=705537436



本例子是旧的城市接口写的例子:

package com.siyehuazhilian.control;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.siyehuazhilian.message.resp.TextMessage;
import com.siyehuazhilian.util.CityCode;
import com.siyehuazhilian.util.Common;
import com.siyehuazhilian.util.MessageUtil;

/**
 * 天气预报,根据指定城市名提供天气情况
 * 
 * @author Administrator
 * 
 */
class TwoChoice {
	/**
	 * 访问城市为东莞时的url
	 */
	private static final String dongGuanUrl = "http://weather.yahooapis.com/forecastrss?w=2161842&u=c";

	/**
	 * 各种天气代号对应的天气
	 */
	private static final String[] dictionaryStrings = { "龙卷风  ", "热带风暴",
			"飓风    ", "强雷阵雨", "雷阵雨  ", "小雨加雪", "雨加冰雹", "雪加冰雹", "冰雨    ",
			"毛毛雨  ", "冻雨    ", "阵雨    ", "阵雨    ", "小雪    ", "零星小雪", "高吹雪  ",
			"雪      ", "冰雹    ", "雨夹雪  ", "尘      ", "雾      ", "薄雾    ",
			"多烟的  ", "大风    ", "有风    ", "寒冷    ", "阴天    ", "夜间阴天", "白天阴天",
			"夜间多云", "白天多云", "夜间清亮", "晴朗    ", "转晴    ", "转晴    ", "雨夹冰雹",
			"热      ", "雷阵雨  ", "雷阵雨  ", "雷阵雨  ", "雷阵雨  ", "大雪    ", "阵雪    ",
			"大雪    ", "多云    ", "雷      ", "阵雪    ", "雷雨    " };

	/**
	 * 得到对应的xml天气预报
	 * 
	 * @param cityCode
	 *            城市代码
	 * @return 对应城市天气预报xml文件
	 * @throws IOException
	 *             服务器出错
	 */
	private static Document getWeatherXML(String cityCode) throws IOException {
		URL url = new URL("http://weather.yahooapis.com/forecastrss?p="
				+ cityCode + "&u=c");
		if (cityCode.equals("dongguan")) {
			url = new URL(dongGuanUrl);
		}
		URLConnection connection = url.openConnection();
		Document Doc = stringToElement(connection.getInputStream());
		return Doc;
	}

	/* 获取天气信息 */
	private static String getWeather(String city) {
		String cityCode = getCityCode(city);
		if (city == null) {
			return "没有找到对应城市\n如果您有查询不到或者查询不准确的情况,请第一时间报告给我们";
		}
		String result = null;
		try {
			Document doc = getWeatherXML(cityCode);
			NodeList nodeList = doc.getElementsByTagName("channel");
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node node = nodeList.item(i);
				NodeList nodeList1 = node.getChildNodes();
				for (int j = 0; j < nodeList1.getLength(); j++) {
					Node node1 = nodeList1.item(j);
					if (node1.getNodeName().equalsIgnoreCase("item")) {
						NodeList nodeList2 = node1.getChildNodes();
						for (int k = 0; k < nodeList2.getLength(); k++) {
							Node node2 = nodeList2.item(k);
							if (node2.getNodeName().equalsIgnoreCase(
									"yweather:forecast")) {
								NamedNodeMap nodeMap = node2.getAttributes();
								Node lowNode = nodeMap.getNamedItem("low");
								Node highNode = nodeMap.getNamedItem("high");
								Node codeNode = nodeMap.getNamedItem("code");
								Node dateNode = nodeMap.getNamedItem("date");
								Node dayNode = nodeMap.getNamedItem("day");
								if (result == null) {
									result = "";
								}
								result = result
										+ dateNode.getNodeValue()
										+ " "
										+ dayNode.getNodeValue()
										+ " \n"
										+ dictionaryStrings[Integer
												.parseInt(codeNode
														.getNodeValue())] + " "
										+ lowNode.getNodeValue() + "~"
										+ highNode.getNodeValue() + "℃ \n";
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result + "\n来自:雅虎天气\n";
	}

	/**
	 * 得到doc对象
	 * 
	 * @param input
	 * @return
	 */
	private static Document stringToElement(InputStream input) {
		try {
			DocumentBuilder db = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			Document doc = db.parse(input);
			return doc;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 根据城市名字得到对应的雅虎天气城市代号
	 * 
	 * @param cityName
	 *            城市名称
	 * @return 城市Code,返回"dongguan"表示搜索的城市是东莞,返回-10086表示错误
	 */
	private static String getCityCode(String cityName) {
		if (cityName.trim().equals("东莞")) {
			return "dongguan";
		}
		CityCode cityCode = new CityCode();
		return cityCode.getHashMap().get(cityName);
	}

	/**
	 * 外部调用方法,得到具体天气
	 * 
	 * @param fromUserName
	 *            用户名
	 * @param toUserName
	 *            公众账户名
	 * @param cityName
	 *            城市名
	 * @return 具体天气
	 */
	public static String getWeatherToUser(String fromUserName,
			String toUserName, String cityName) {
		cityName = cityName.trim();
		if (cityName.equals("2") || cityName.equals("天气")) {
			// 回复文本消息
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setFuncFlag(0);
			textMessage.setContent(Common.getTranslationMenu());
			return MessageUtil.textMessageToXml(textMessage);
		}

		cityName = cityName.replace("天气", "").replace("+", "").replace("2", "")
				.replace(".", "");

		// 创建图文消息
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);// 用户账号
		textMessage.setFromUserName(toUserName);// 公众账号
		textMessage.setCreateTime(new Date().getTime());// 消息时间
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);// 返回类型为文本
		textMessage.setFuncFlag(0);// 标志位
		textMessage.setContent("查询城市: " + cityName + "\n"
				+ getWeather(cityName));
		return MessageUtil.textMessageToXml(textMessage);
	}

	public static void main(String[] args) {
		String cityName = "天气深圳";
		cityName = cityName.replace("天气", "").replace("+", "").replace("2", "")
				.replace(".", "");
		;
		System.out.println(cityName);
		System.out.println(cityName.replace("^天气[\\+ ~!@#%^-_=]?", ""));
		System.out.println(getWeather(cityName));
	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的使用Weka Java API预测天气的示例代码: ```java import java.io.BufferedReader; import java.io.FileReader; import weka.classifiers.Classifier; import weka.classifiers.bayes.NaiveBayes; import weka.classifiers.evaluation.Evaluation; import weka.core.Instance; import weka.core.Instances; public class WeatherPredictor { public static void main(String[] args) throws Exception { // 1. 加载数据集 BufferedReader reader = new BufferedReader(new FileReader("weather.arff")); Instances data = new Instances(reader); reader.close(); // 2. 设置类别属性 data.setClassIndex(data.numAttributes() - 1); // 3. 构建决策树分类器 Classifier classifier = new NaiveBayes(); classifier.buildClassifier(data); // 4. 交叉验证评估分类器 Evaluation eval = new Evaluation(data); eval.crossValidateModel(classifier, data, 10, new java.util.Random(1)); System.out.println(eval.toSummaryString()); // 5. 预测新实例 Instance instance = new Instance(4); instance.setDataset(data); instance.setValue(0, "sunny"); instance.setValue(1, "hot"); instance.setValue(2, "high"); instance.setValue(3, "weak"); double[] probabilities = classifier.distributionForInstance(instance); System.out.println("Probability of each class:"); for (int i = 0; i < data.classAttribute().numValues(); i++) { System.out.println(data.classAttribute().value(i) + ": " + probabilities[i]); } } } ``` 在本例中,我们使用了Weka自带的天气数据集(weather.arff)。在代码中,我们首先加载数据集,并将其类别属性设置为最后一个属性。然后,我们使用朴素贝叶斯分类器构建模型,并对模型进行10折交叉验证评估。最后,我们使用朴素贝叶斯分类器对新实例进行分类,并输出每个类别的概率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值