2012-12-16 26 views
1

所以我的標題可能無法解釋所有的事情,所以我會更好地解釋,我正在研究這個擴展的鉻,從我在網上找到的dat文件抓取同義詞來自MIT的某人。我已經得到了我的大部分想法用Java編寫的(我的母語)的,在這兒,所以你可以看到我想要做的:現在JavaScript和谷歌瀏覽器,輸入流和陣列

import java.io.BufferedReader; 
import java.io.InputStreamReader; 
import java.net.URL; 
import java.util.ArrayList; 

public class Grabber { 

/** 
* @param args 
*/ 
public static void main(String[] args) throws Exception { 

    URL mit = new URL(
      "http://mit.edu/~mkgray/jik/sipbsrc/src/thesaurus/old-thesaurus/lib/thesaurus.dat"); 
    BufferedReader in = new BufferedReader(new InputStreamReader(
      mit.openStream())); 

    String inputLine; 
    while ((inputLine = in.readLine()) != null) { 
     if (inputLine.startsWith("spoken")) { 
      ArrayList<String> list = new ArrayList<String>(); 
      String[] synonyms = inputLine.substring("spoken".length()) 
        .split(" "); 
      for (String toPrint : synonyms) { 
       if (toPrint.length() > 0) { 
        list.add(toPrint.trim()); 
       } 
      } 
      for (String toPrint : list) { 
       System.out.println(toPrint); 
      } 
     } 
    } 
    in.close(); 
    } 
} 

,與語言的我的「Codecademy網站」知識,我不知道Chrome的JavaScript API中包含的所有庫。我們應該開始尋找完成這項任務嗎?哦,我還需要弄清楚如何在JavaScript中創建數組,就像我上面寫的集合一樣。

+0

Codeacademy沒有教如何做一個數組,你可能需要趕上了一點。一些提示:1.帶有'XHR'的grub文件; 2.'String.split()'; 3.使用'Object'作爲字典。 – xiaoyi

回答

1

下面是一個例子:

var xhr = new XMLHttpRequest(); // Use XMLHttpRequest to fetch resources from the Web 
xhr.open("GET", // HTTP GET method 
    "http://mit.edu/~mkgray/jik/sipbsrc/src/thesaurus/old-thesaurus/lib/thesaurus.dat", 
    true // asynchronous 
); 
xhr.onreadystatechange = (function() 
{ 
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) // success 
    { 
     // data fetched in xhr.responseText, now parse it 
     var inputLines = xhr.responseText.split(/\r|\n|\r\n/); //Split them into lines 
     /* A quick and brief alternative to 
     while ((inputLine = in.readLine()) != null) { 
       if (inputLine.startsWith("spoken")) { 
       ... 
      } 
     } */ 
     inputLines.filter(function(inputLine) 
     { 
      // You can also use 
      // return inputLine.substr(0, 6) == "spoken"; 
      // if you are not familiar with regular expressions. 
      return inputLine.match(/^spoken/); 
     }).forEach(inputLine) 
     { 
      var list = []; 
      var synonyms = inputLine.substring("spoken".length).split(" "); 
      synonyms.fonEach(function(toPrint) 
      { 
       if(toPrint.length > 0) 
        list.push(toPrint.replace(/^\s+|\s+$/g, '')); 
        //toPrint.replace(/^\s+|\s+$/g, '') is similar to toPrint.trim() in Java 
        //list.push(...) is used to add a new element in the array list. 
      }); 
      list.forEach(function(toPrint) 
      { 
       // Where do you want to put your output? 
      }); 
     }); 
    } 
}); 
xhr.send(); // Send the request and fetch the data.