Java實現(xiàn)統(tǒng)計文檔中關鍵字出現(xiàn)的次數(shù)
更新時間:2022年05月12日 09:31:35 作者:錯過了時間
這篇文章主要為大家分享了利用Java語言實現(xiàn)統(tǒng)計關鍵字在文檔中出現(xiàn)的次數(shù)的方法,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下
該代碼簡易實現(xiàn)了獲取URL地址后對文檔進行關鍵字統(tǒng)計的功能。具體的自己看吧
1.實現(xiàn)URL文檔的拷貝
import java.util.Scanner;
import java.util.regex.Pattern;
import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.UIManager;
import java.awt.*;
import javax.swing.plaf.FontUIResource;
public class TestURL {
static String getUserKeyWords=null; //獲取用戶選擇的關鍵詞
public static void main(String[] args) {
File copyfile=new File("D:/newTest.txt");
InputStream in=null;
BufferedReader br=null; //字符流寫入
BufferedWriter out=null; //字符流寫出
String urladdress=null; //獲取用戶輸入的URL地址
try
{
UIManager.put("JOptionPane.messageFont",new FontUIResource(new Font("宋體",Font.BOLD,20)));
String getUserURL=JOptionPane.showInputDialog(null,"URL地址:\n","輸入URL地址",JOptionPane.PLAIN_MESSAGE);
String urlAddr=getUserURL.substring(getUserURL.lastIndexOf("/"));
copyfile=new File("D:/"+urlAddr);
getUserKeyWords=JOptionPane.showInputDialog(null,"關鍵字查詢:\n","關鍵字",JOptionPane.PLAIN_MESSAGE);
//URL url=new URL("http://news.cctv.com/2019/06/19/ARTIhqziOpWz2COTyHFW063b190619.shtml"); //獲取URL地址
URL url=new URL(getUserURL); //獲取URL地址
HttpURLConnection urlC=(HttpURLConnection)url.openConnection(); //由URL獲取URLConnection對象
in=urlC.getInputStream(); //獲取urlC的輸入流
br=new BufferedReader(new InputStreamReader(in,"UTF-8")); //將url默認的字節(jié)流轉成字符流,并以UTF-8的格式寫入文檔
out=new BufferedWriter(new FileWriter(copyfile)); //將獲取的信息寫入到TestURL文檔中
String length=null;
while ((length=br.readLine())!=null)
{
out.write(Html2Text(length));
out.newLine();
}
}
catch (Exception e)
{
e.getMessage();
}finally{
System.out.println("拷貝完成!");
try{
if (in!=null){in.close();}
if (out!=null){out.close();}
if (br!=null){br.close();}
}catch(Exception ee){
ee.getMessage();
}
}
TextFileSearch search = new TextFileSearch();
search.SearchKeyword(copyfile, getUserKeyWords);
} //程序到這就結束了 ,下面是不同方法實現(xiàn)對html的剔除功能,可以忽略
//從html中提取純文本 ,這部分其實沒什么用,最開始想截取html中的字符串,后面檢查也沒啥用,就沒刪除,保留著
public static String Html2Text(String inputString) {
String htmlStr = inputString; // 含html標簽的字符串
String textStr = "";
java.util.regex.Pattern p_script;
java.util.regex.Matcher m_script;
java.util.regex.Pattern p_style;
java.util.regex.Matcher m_style;
java.util.regex.Pattern p_html;
java.util.regex.Matcher m_html;
try {
String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定義script的正則表達式{或<script[^>]*?>[\\s\\S]*?<\\/script>
String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定義style的正則表達式{或<style[^>]*?>[\\s\\S]*?<\\/style>
String regEx_html = "<[^>]+>"; // 定義HTML標簽的正則表達式
p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 過濾script標簽
p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 過濾style標簽
p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 過濾html標簽
textStr = htmlStr;
} catch (Exception e) {System.err.println("Html2Text: " + e.getMessage()); }
//剔除空格行
textStr=textStr.replaceAll("[ ]+", " ");
textStr=textStr.replaceAll("(?m)^\\s*$(\\n|\\r\\n)", "");
return textStr;// 返回文本字符串
}
/*//從html中提取純文本,這個部分是簡易實現(xiàn)html剔除,只能部分篩選
public static String stripHT(String strHtml){
String txtcontent = strHtml.replaceAll("</?[^>]+>", ""); //剔出<html>的標簽
txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");//去除字符串中的空格,回車,換行符,制表符
return txtcontent;
}*/
/* //這個是利用java自帶的類實現(xiàn)html剔除功能,基本上沒怎么用,這部分可以忽略
import java.io.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;
public class Html2Text extends HTMLEditorKit.ParserCallback {
StringBuffer s;
public Html2Text() {}
public void parse(Reader in) throws IOException {
s = new StringBuffer();
ParserDelegator delegator = new ParserDelegator();
// the third parameter is TRUE to ignore charset directive
delegator.parse(in, this, Boolean.TRUE);
}
public void handleText(char[] text, int pos) {
s.append(text);
}
public String getText() {
return s.toString();
}
public static void main (String[] args) {
try {
// the HTML to convert
//Reader in=new StringReader("string");
FileReader in = new FileReader("java-new.html");
Html2Text parser = new Html2Text();
parser.parse(in);
in.close();
System.out.println(parser.getText());
}
catch (Exception e) {
e.printStackTrace();
}
}
}*/
}2.實現(xiàn)關鍵詞在文檔的查詢功能
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import javax.swing.UIManager;
import javax.swing.*;
import java.awt.*;
import javax.swing.plaf.FontUIResource;
/**
* 對文本文件的關鍵詞進行搜索
*/
public class TextFileSearch {
TestURL tt;
public void SearchKeyword(File file,String keyword) {
//參數(shù)校驗
verifyParam(file, keyword);
//行讀取
LineNumberReader lineReader = null;
try {
lineReader = new LineNumberReader(new FileReader(file));
String readLine = null;
int times = 0;//出現(xiàn)的次數(shù)
while((readLine =lineReader.readLine()) != null){
//判斷每一行中,出現(xiàn)關鍵詞的次數(shù)
int index = 0; //獲得readLine的對象值
int next = 0; //定義開始查找關鍵字的序列號
//int times = 0;//出現(xiàn)的次數(shù)
//判斷次數(shù)
while((index = readLine.indexOf(keyword,next)) != -1) { //從每行的第0個索引開始遍歷關鍵字
next = index + keyword.length(); //下一次的遍歷序號為序列號+關鍵字長度
times++;//次數(shù)加1
}
/*if(times > 0) {
//System.out.println("第"+ lineReader.getLineNumber() +"行" + "出現(xiàn) "+keyword+" 次數(shù): "+times);
}*/
}
if (times>0)
{
UIManager.put("JOptionPane.messageFont",new FontUIResource(new Font("宋體",Font.BOLD,20)));
JOptionPane.showMessageDialog(null,"關鍵字"+"@"+tt.getUserKeyWords+"@"+"共有"+times+"個");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//關閉流
close(lineReader);
}
}
/**
* 參數(shù)校驗
*/
private void verifyParam(File file, String keyword) {
//對參數(shù)進行校驗證
if(file == null ){
throw new NullPointerException("the file is null");
}
if(keyword == null || keyword.trim().equals("")){
throw new NullPointerException("the keyword is null or \"\" ");
}
if(!file.exists()) {
throw new RuntimeException("the file is not exists");
}
//非目錄
if(file.isDirectory()){
throw new RuntimeException("the file is a directory,not a file");
}
//可讀取
if(!file.canRead()) {
throw new RuntimeException("the file can't read");
}
}
/**
* 關閉流
*/
private void close(Closeable able){
if(able != null){
try {
able.close();
} catch (IOException e) {
e.printStackTrace();
able = null;
}
}
}
}3.顯示效果
URL地址獲取效果圖

關鍵字查詢界面

查詢后效果圖

到此這篇關于Java實現(xiàn)統(tǒng)計文檔中關鍵字出現(xiàn)的次數(shù)的文章就介紹到這了,更多相關Java關鍵字次數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java?ObjectMapper的使用和使用過程中遇到的問題
在Java開發(fā)中,ObjectMapper是Jackson庫的核心類,用于將Java對象序列化為JSON字符串,或者將JSON字符串反序列化為Java對象,這篇文章主要介紹了Java?ObjectMapper的使用和使用過程中遇到的問題,需要的朋友可以參考下2024-07-07
Java中ByteArrayOutputStream亂碼問題解決
本文主要介紹了Java中ByteArrayOutputStream亂碼問題解決,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07
Java 文件上傳與路徑處理之Paths.get()、resolve()、transferTo()的用法詳解
本文詳細解析了如何使用Java的Paths.get()、resolve()和Spring的transferTo()方法處理文件上傳功能,并給出了完整的代碼示例,感興趣的朋友跟隨小編一起看看吧2024-10-10
java使用Runtime執(zhí)行系統(tǒng)命令遇到的問題
這篇文章主要介紹了java使用Runtime執(zhí)行系統(tǒng)命令遇到的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11

