gpt4 book ai didi

java - 我需要打印出特定 url 地址的段落中每个单词的使用次数

转载 作者:行者123 更新时间:2023-12-01 14:44:11 24 4
gpt4 key购买 nike

我正在尝试计算与特定 URL 地址关联的单词数,并按照单词出现的次数按顺序打印单词。现在它读入文件并计算单词数,但它会逐行打印出来,而不是对整个段落进行计数。有什么帮助让它阅读全文并打印出单词在整个段落中如果有他们的出现那就太好了。

public static void main(String[] args) 
{
try {
URL url = new URL("http://webpagehere.txt");
BufferedReader reader = new BufferedReader
(new InputStreamReader(url.openStream()));
String line;
int i=0;
while ((line = reader.readLine()) != null) {
i++;
System.out.println("Line " + i + "\t" + line);
// Create a TreeMap to hold words as key and count as value
Map<String, Integer> map = new TreeMap<String, Integer>();

String[] words = line.split("[ \n\t\r.,;:!?(){}]");
for (int j = 0; j < words.length; j++) {
String key = words[j].toLowerCase();

if (key.length() > 0) {
if (!map.containsKey(key)) {
map.put(key, 1);
}
else {
int value = map.get(key);
value++;
map.put(key, value);
}
}
}

// Get all entries into a set
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();

// Get key and value from each entry
for (Map.Entry<String, Integer> entry: entrySet)
System.out.println(entry.getKey() + "\t" + entry.getValue());


}

reader.close();
} catch (UnknownHostException e) {
JOptionPane.showMessageDialog(null, "Unknown host. Abort.");
} catch (NoRouteToHostException e) {
JOptionPane.showMessageDialog(null,
"Cannot reach remote host. Abort.");
} catch (java.lang.Exception e) {
e.printStackTrace();
}

}
}

最佳答案

您只需将 Map 的初始化和打印移到 while 循环之外即可。

public static void main(String[] args) 
{
try {
URL url = new URL("http://webpagehere.txt");
BufferedReader reader = new BufferedReader
(new InputStreamReader(url.openStream()));
String line;
int i=0;
Map<String, Integer> map = new TreeMap<String, Integer>();
while ((line = reader.readLine()) != null) {
i++;
System.out.println("Line " + i + "\t" + line);
// Create a TreeMap to hold words as key and count as value

String[] words = line.split("[ \n\t\r.,;:!?(){}]");
for (int j = 0; j < words.length; j++) {
String key = words[j].toLowerCase();

if (key.length() > 0) {
if (!map.containsKey(key)) {
map.put(key, 1);
}
else {
int value = map.get(key);
value++;
map.put(key, value);
}
}
}
}
reader.close();

// Get all entries into a set
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();

// Get key and value from each entry
for (Map.Entry<String, Integer> entry: entrySet)
System.out.println(entry.getKey() + "\t" + entry.getValue());

} catch (UnknownHostException e) {
System.out.println("Unknown host. Abort.");
} catch (NoRouteToHostException e) {
System.out.println("Cannot reach remote host. Abort.");
} catch (java.lang.Exception e) {
e.printStackTrace();
}

}

关于java - 我需要打印出特定 url 地址的段落中每个单词的使用次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15620904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com