[英]How to count the number of times “.” appears in a webpage?
我想瀏覽一個html頁面並計算“。”的次數。 (句點)顯示。 在這里,我有一些讀取html的代碼,並打印出所需的輸出。
我當時正在考慮修改此代碼,但是看到這是一個簡單的問題,也許我們不需要經歷修改它的麻煩。 相反,我們可以直接編寫新程序。
這是我閱讀網頁html的代碼(很多代碼應該是不必要的代碼):
import edu.duke.*;
public class URLFinder {
public StorageResource findURLs(String url) {
URLResource page = new URLResource(url);
String source = page.asString();
StorageResource store = new StorageResource();
int start = 0;
while (true) {
int index = source.indexOf("href=", start);
if (index == -1) {
break;
}
int firstQuote = index+6; // after href="
int endQuote = source.indexOf("\"", firstQuote);
String sub = source.substring(firstQuote, endQuote);
if (sub.contains(".")) {
store.add(sub);
}
start = endQuote + 1;
}
return store;
}
public void testURL() {
StorageResource s1 = findURLs("http://www.dukelearntoprogram.com/course2/data/newyorktimes.html");
//StorageResource s2 = findURLs("http://www.doctorswithoutborders.org");
for (String link : s1.data()) {
System.out.println(link);
}
System.out.println("size = " + s1.size());
//System.out.println("size = " + s2.size());
}
}
您可以執行以下操作:
int count = 0;
for (char c : source.toCharArray()) {
if (c == '.') {
count++;
}
}
或者,利用Apache Commons庫及其強大的StringUtils函數: StringUtils.countMatches(String string, String subStringToCount)
。 然后,您只需執行StringUtils.countMatches(source, ".");
得到周期數。
如果要將其放入當前程序中,則需要編輯findUrls
函數,在String source = page.asString();
之后插入計數String source = page.asString();
。
或者,如果您只是想在自己的功能中使用此功能:
public int countPeriods(String url) {
URLResource page = new URLResource(url);
String source = page.asString();
int count = 0;
for (char c : source.toCharArray()) {
if (c == '.') {
count++;
}
}
return count;
}
現在您需要做的就是將url作為字符串傳遞給函數,它將返回您的計數。
一種方法是使用indexOf
方法:
int index = -1;
int count = 0;
String source = ...;
while((index = source.indexOf(".", ++index) != -1)
count++
正如@TJCrowder指出的那樣,可能是需要讓某些腳本執行的情況。 如果是這樣的話,請參考這個以前的SO問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.