溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java統(tǒng)計英文句子中出現(xiàn)次數(shù)最多的單詞并計算出現(xiàn)次數(shù)的方法

發(fā)布時間:2020-10-14 15:33:21 來源:腳本之家 閱讀:322 作者:handsome_ZHANG 欄目:編程語言

本文實例講述了Java統(tǒng)計英文句子中出現(xiàn)次數(shù)最多的單詞并計算出現(xiàn)次數(shù)的方法。分享給大家供大家參考,具體如下:

import java.util.*;
/**
 * 統(tǒng)計出現(xiàn)次數(shù)最多的單詞和它出現(xiàn)的次數(shù)
 * 
 * @author ZHR
 */
public class CountWord {
 public static String[] strTostrArray(String str) {
  /*
   * 將非字母字符全部替換為空格字符" " 得到一個全小寫的純字母字符串包含有空格字符
   */
  str = str.toLowerCase();// 將字符串中的英文部分的字符全部變?yōu)樾?  String regex = "[\\W]+";// 非字母的正則表達(dá)式 --\W:表示任意一個非單詞字符
  str = str.replaceAll(regex, " ");
  String[] strs = str.split(" "); // 以空格作為分隔符獲得字符串?dāng)?shù)組
  return strs;
 }
 public static void countword(String[] strs) {
  /*
   * 建立字符串(String)出現(xiàn)次數(shù)(Integer)的映射
   */
  HashMap<String, Integer> strhash = new HashMap<String, Integer>();
  Integer in = null;// 用于存放put操作的返回值
  for (String s : strs) {// 遍歷數(shù)組 strs
   in = strhash.put(s, 1);
   if (in != null) {// 判斷如果返回的不是null,則+1再放進(jìn)去就是出現(xiàn)的次數(shù)
    strhash.put(s, in + 1);
   }
  }
  Set<java.util.Map.Entry<String, Integer>> entrySet = strhash.entrySet();
  String maxStr = null;// 用于存放出現(xiàn)最多的單詞
  int maxValue = 0;// 用于存放出現(xiàn)最多的次數(shù)
  for (java.util.Map.Entry<String, Integer> e : entrySet) {
   String key = e.getKey();
   Integer value = e.getValue();
   if (value > maxValue) {
    maxValue = value;// 這里有自動拆裝箱
    maxStr = key;
   }
  }
  System.out.println("出現(xiàn)最多的單詞是:" + maxStr + "出現(xiàn)了" + maxValue + "次");
 }
 @SuppressWarnings("resource")
 public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);
  System.out.println("請輸入一行英文句子:");
  String str = scan.nextLine();
  System.out.println("輸入的英文句子為:" + str);
  String[] strs = strTostrArray(str);
  countword(strs);
 }
}

運行結(jié)果:

Java統(tǒng)計英文句子中出現(xiàn)次數(shù)最多的單詞并計算出現(xiàn)次數(shù)的方法

PS:這里再為大家推薦2款非常方便的統(tǒng)計工具供大家參考使用:

在線字?jǐn)?shù)統(tǒng)計工具:
http://tools.jb51.net/code/zishutongji

在線字符統(tǒng)計與編輯工具:
http://tools.jb51.net/code/char_tongji

更多關(guān)于java算法相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》

希望本文所述對大家java程序設(shè)計有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI