在字符串中查找特定的字符序列

时间:2019-05-24 17:55:23

标签: java

我正在尝试编写代码以获取用户输入城市的纬度和经度。 我编写了一个代码,该代码搜索网站,然后将其HTML数据存储在字符串中。 现在,我想在字符串(网站的HTML)中搜索值。

我已经研究过API和HTML解析器,但是它们对我来说太复杂了(我还在上学,只是刚开始),所以请不要推荐它们,除非没有它们绝对不可能。 代码:

import java.net.*;
import java.io.*;
import java.util.Scanner;
import static java.lang.System.*;
class websearch {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //gets the city
        out.println("enter city, add plus between multiple words");
        String term = sc.nextLine();

        try {URL url = new URL("http://www.geonames.org/search.html?q=" + term + "&country=");
        URLConnection ucl = url.openConnection();
        InputStream stream = ucl.getInputStream();
        int i;
        //the string in which the html code will be stored
        String code = " ";
        while ((i=stream.read())!= -1) {
            code += Character.toString((char)i);
        }
        //printing the html, only for testing
        System.out.print(code);
    } catch(Exception e) {
        System.out.println("error");
    }
    }
}

此代码打印的字符串太大,无法粘贴到此处,但是我要查找的值如下所示:

<td nowrap="">N 40° 42' 51''</td>
<td nowrap="">W 74° 0' 21''</td>

如何找到此字符序列,然后仅将纬度和经度存储在变量中?

2 个答案:

答案 0 :(得分:1)

This教程应该对您有所帮助。它讨论了如何在不实际使用Google Maps API的情况下获取地理编码数据。如果您遵循它说的那样,则应该有一个轻松的时间来实施它。

最终结果是,您将输入所需位置的街道地址,并将返回可搜索变量中的纬度和经度。

初级工人阶级

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;

public class OpenStreetMapUtils {

    public final static Logger log = Logger.getLogger("OpenStreeMapUtils");

    private static OpenStreetMapUtils instance = null;
    private JSONParser jsonParser;

    public OpenStreetMapUtils() {
        jsonParser = new JSONParser();
    }

    public static OpenStreetMapUtils getInstance() {
        if (instance == null) {
            instance = new OpenStreetMapUtils();
        }
        return instance;
    }

    private String getRequest(String url) throws Exception {

        final URL obj = new URL(url);
        final HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("GET");

        if (con.getResponseCode() != 200) {
            return null;
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }

    public Map<String, Double> getCoordinates(String address) {
        Map<String, Double> res;
        StringBuffer query;
        String[] split = address.split(" ");
        String queryResult = null;

        query = new StringBuffer();
        res = new HashMap<String, Double>();

        query.append("http://nominatim.openstreetmap.org/search?q=");

        if (split.length == 0) {
            return null;
        }

        for (int i = 0; i < split.length; i++) {
            query.append(split[i]);
            if (i < (split.length - 1)) {
                query.append("+");
            }
        }
        query.append("&format=json&addressdetails=1");

        log.debug("Query:" + query);

        try {
            queryResult = getRequest(query.toString());
        } catch (Exception e) {
            log.error("Error when trying to get data with the following query " + query);
        }

        if (queryResult == null) {
            return null;
        }

        Object obj = JSONValue.parse(queryResult);
        log.debug("obj=" + obj);

        if (obj instanceof JSONArray) {
            JSONArray array = (JSONArray) obj;
            if (array.size() > 0) {
                JSONObject jsonObject = (JSONObject) array.get(0);

                String lon = (String) jsonObject.get("lon");
                String lat = (String) jsonObject.get("lat");
                log.debug("lon=" + lon);
                log.debug("lat=" + lat);
                res.put("lon", Double.parseDouble(lon));
                res.put("lat", Double.parseDouble(lat));

            }
        }

        return res;
    }
}

如何调用上述工人阶级:

public class GetCoordinates {

    static String address = "The White House, Washington DC";

    public static void main(String[] args) {
        Map<String, Double> coords;
        coords = OpenStreetMapUtils.getInstance().getCoordinates(address);
        System.out.println("latitude :" + coords.get("lat"));
        System.out.println("longitude:" + coords.get("lon"));
    }
}

答案 1 :(得分:0)

使用XPath是一种简单的方法。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpath_expression>);

至于,尝试如下操作: / xxx / td [@nowrap =''] / text()