在一些項目中可能需要對一段字符串中的單詞進行統(tǒng)計,我在這里寫了一個簡單的demo,有需要的同學(xué)可以拿去看一下。
不說廢話了直接貼代碼:
實現(xiàn)代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
/** * 統(tǒng)計各個單詞出現(xiàn)的次數(shù) * @param text */ public static void findEnglishNum(String text){ //找出所有的單詞 String[] array = { "." , " " , "?" , "!" }; for ( int i = 0 ; i < array.length; i++) { text = text.replace(array[i], "," ); } String[] textArray = text.split( "," ); //遍歷 記錄 Map<String, Integer> map = new HashMap<String, Integer>(); for ( int i = 0 ; i < textArray.length; i++) { String key = textArray[i]; //轉(zhuǎn)為小寫 String key_l = key.toLowerCase(); if (! "" .equals(key_l)){ Integer num = map.get(key_l); if (num == null || num == 0 ){ map.put(key_l, 1 ); } else if (num > 0 ){ map.put(key_l, num+ 1 ); } } } //輸出到控制臺 System.out.println( "各個單詞出現(xiàn)的頻率為:" ); Iterator<String> iter = map.keySet().iterator(); while (iter.hasNext()){ String key = iter.next(); Integer num = map.get(key); System.out.println(key + "\n\t\t" + num + "次\n-------------------" ); } } |
測試代碼:
1
2
3
|
public static void main(String[] args) { String text = "Welcome welcome to ADempiere, a commons-based peer-production of Open Source ERP Applications. This Wiki is for the global community to contribute and share know-how and domain expertise. We hope you can find as much open information and participate in making it most usable for everyone. This project has a bazaar of Citizens with a Community Council Team which work in theFunctional Team and Technical Team along the Software Development Procedure supported and funded by the foundation ADempiere" ; findEnglishNum(text); } |
運行結(jié)果:
后面還有一些沒有全部截下來
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持服務(wù)器之家!
原文鏈接:http://www.cnblogs.com/LFBlog/p/6240906.html