사전 웹 사이트의 웹 페이지를 구문 분석하는 단어 정의 가져 오기 프로그램을 작성했습니다. 모든 웹 페이지가 정확히 동일한 HTML 구조를 가지고있는 것은 아니므로 대부분의 경우를 지원하는 여러 가지 구문 분석 방법을 구현해야했습니다.반복적 인 대체 메커니즘을 구현하는 디자인 패턴
아래는 내가 지금까지 해본 적이있다. 이것은 꽤 못생긴 코드이다. 나는 N을 구현할 수 있도록 반복적 인 대체 메커니즘 어떤 종류의 코딩의 가장 깨끗한 방법이 될 것 어떻게 생각하십니까
는 방법을 분석하는 순서 (구문 분석 오류가 다음 구문 분석을 트리거합니다 (더 적절한 용어가있을 수 있습니다) IOException과 같은 예외는 프로세스를 중단해야합니다.)
public String[] getDefinition(String word) {
String[] returnValue = { "", "" };
returnValue[0] = word;
Document doc = null;
try {
String finalUrl = String.format(_baseUrl, word);
Connection con = Jsoup.connect(finalUrl).userAgent("Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
doc = con.get();
// *** Case 1 (parsing method that works for 80% of the words) ***
String basicFormOfWord = doc.select("DIV.luna-Ent H2.me").first().text().replace("·", "");
String firstPartOfSpeech = doc.select("DIV.luna-Ent SPAN.pg").first().text();
String firstDef = doc.select("DIV.luna-Ent DIV.luna-Ent").first().text();
returnValue[1] = "<b>" + firstPartOfSpeech + "</b><br/>" + firstDef;
returnValue[0] = basicFormOfWord;
} catch (NullPointerException e) {
try {
// *** Case 2 (Alternate parsing method - for poorer results) ***
String basicFormOfWord = doc.select("DIV.results_content p").first().text().replace("·", "");
String firstDef = doc.select("DIV.results_content").first().text().replace(basicFormOfWord, "");
returnValue[1] = firstDef;
returnValue[0] = basicFormOfWord;
} catch (Exception e2) {
e2.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return returnValue;
}
당신의 체인을 고려할 수 세바스티앙의 주석으로 코드를 수정 책임 [패턴] (http://www.javacamp.org/designPattern/chains.html) – Renard