問題說明:
這是自己嘗試寫的字頻統(tǒng)計的代碼,但是調(diào)試時沒有輸出,于是在代碼中間插入了很多輸出語句,發(fā)現(xiàn)程序無法進入for循環(huán)體,程序中所有的for循環(huán)體都直接被跳過了。
代碼如下:
import java.io.*;
import java.util.*;
public class Counter {
public static String txt2String(File file){
StringBuilder result = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(file));//構造一個BufferedReader類來讀取文件
String s = null;
while((s = br.readLine())!=null){ //使用readLine方法,一次讀一行
result.append(System.lineSeparator()+s);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return result.toString();
}
public static void count(String str) {
String[] strarray = str.split("\b");
ArrayList<String> list = new ArrayList<String>();
ArrayList<Integer> num = new ArrayList<Integer>();
int temp = 1;
System.out.println("list和num初始化完成。");
System.out.println("開始剔除重復并計數(shù)。");
for(int i = 0; i<list.size(); i++) {
System.out.println("進入循環(huán)體。");
int flag = 0;
for(int j = 0; j<i; j++) {
if(strarray[j].equals(strarray[i])) {
flag = flag+1;
for(int m =0; m<list.size(); m++) {
if(strarray[m].equals(strarray[j])) {
temp++;
num.add(j,temp);
}
}
System.out.println("遇到重復單詞。");
break;
}
else {
System.out.println("這次沒遇到重復單詞。");
}
}
if(flag==0) {
list.add(i,strarray[i]);
System.out.println("成功添加一個新單詞。");
}
}
System.out.println("準備輸出最終統(tǒng)計結果。");
for(int i =0; i<list.size(); i++) {
System.out.print(list.get(i));
System.out.print(":出現(xiàn)了");
System.out.print(num.get(i));
System.out.println("次");
}
}
public static void main(String[] args) {
File file = new File("D:\\java eclipse\\eclipse-workspace\\Counter\\src\\news.txt");
String str = new String(txt2String(file));
count(str);
}
}
控制臺輸出結果如下:
糾錯嘗試:
查了ArrayList遍歷和add的用法,感覺應該沒錯。(但是我是新手 第一次用ArrayList也不是很確定,不清楚是不是和這個有關)
搜索了無法進入for循環(huán)的情況,沒找到什么有價值的信息。
PS:
希望能有人幫忙解答我的問題或者可以提供字頻統(tǒng)計程序的源碼參考,謝謝!
代碼中有很多問題,基本上思路就是錯的。1,讀文件有問題,txt2String中System.lineSeparator()應該加s后面。2,分割字符串有問題,count函數(shù)str.split("b");未考慮其它分隔符的情況,正確的做法是用正則表達式str.split("\s");。3,初始化后,list.size()=0,當然不會進入循環(huán)。
如果只想要代碼的話看這里,java 字符串詞頻統(tǒng)計實例代碼
下面代碼是連接中的內(nèi)容
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WordsStatistics {
class Obj {
int count ;
Obj(int count){
this.count = count;
}
}
public List<WordCount> statistics(String word) {
List<WordCount> rs = new ArrayList<WordCount>();
Map <String,Obj> map = new HashMap<String,Obj>();
if(word == null ) {
return null;
}
word = word.toLowerCase();
word = word.replaceAll("'s", "");
word = word.replaceAll(",", "");
word = word.replaceAll("-", "");
word = word.replaceAll("\\.", "");
word = word.replaceAll("'", "");
word = word.replaceAll(":", "");
word = word.replaceAll("!", "");
word = word.replaceAll("\n", "");
String [] wordArray = word.split(" ");
for(String simpleWord : wordArray) {
simpleWord = simpleWord.trim();
if (simpleWord != null && !simpleWord.equalsIgnoreCase("")) {
Obj cnt = map.get(simpleWord);
if ( cnt!= null ) {
cnt.count++;
}else {
map.put(simpleWord, new Obj(1));
}
}
}
for(String key : map.keySet()) {
WordCount wd = new WordCount(key,map.get(key).count);
rs.add(wd);
}
Collections.sort(rs, new java.util.Comparator<WordCount>(){
@Override
public int compare(WordCount o1, WordCount o2) {
int result = 0 ;
if (o1.getCount() > o2.getCount() ) {
result = -1;
}else if (o1.getCount() < o2.getCount()) {
result = 1;
}else {
int strRs = o1.getWord().compareToIgnoreCase(o2.getWord());
if ( strRs > 0 ) {
result = 1;
}else {
result = -1 ;
}
}
return result;
}
});
return rs;
}
public static void main(String args[]) {
String word = "Pinterest is might be aa ab aa ab marketer's dream - ths site is largely used to curate products " ;
WordsStatistics s = new WordsStatistics();
List<WordCount> rs = s.statistics(word);
for(WordCount word1 : rs) {
System.out.println(word1.getWord()+"*"+word1.getCount());
}
}
}
后來自己又重新查了一下資料,重新寫了一下。
用map來存儲單詞和頻數(shù)顯然更加合理一些,用Comparator來做升降序排列。
這是老師給的一道實驗題,發(fā)一下題目吧,和我一樣的初學者有興趣也可以寫著試一試。
題目如下:
我把后來寫的代碼重新發(fā)一下。
代碼如下:
import java.io.*;
import java.io.FileReader;
import java.util.*;
import java.util.Map.Entry;
public class Counter {
public static List<String> txt2String(File file) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("D:\\java eclipse\\eclipse-workspace\\Counter\\src\\news.txt"));
List<String> lists = new ArrayList<String>(); //存儲過濾后單詞的列表
String readLine = null;
while((readLine = br.readLine()) != null){
String[] wordsArr1 = readLine.split("[^a-zA-Z]"); //過濾出只含有字母的
for (String word : wordsArr1) {
if(word.length() != 0){ //去除長度為0的行
lists.add(word);
}
}
}
br.close();
return lists;
}
public static void count(List<String> lists) {
Map<String, Integer> wordsCount = new TreeMap<String,Integer>(); //存儲單詞計數(shù)信息,key值為單詞,value為單詞數(shù)
//單詞的詞頻統(tǒng)計
for (String li : lists) {
if(wordsCount.get(li) != null){
wordsCount.put(li,wordsCount.get(li) + 1);
}else{
wordsCount.put(li,1);
}
}
ArrayList<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(wordsCount.entrySet());
Collections.sort(list,new Comparator<Map.Entry<String,Integer>>(){
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue(); //降序
//return o1.getValue() - o2.getValue(); //升序
}
});
//for(Map.Entry<String,Integer> m:wordsCount.entrySet()){
// System.out.println(m.getKey()+" "+m.getValue());
// }
for(int i = 0; i<list.size(); i++){
System.out.println(list.get(i).getKey()+ ": " +list.get(i).getValue());
}
}
public static void main(String[] args) throws Exception{
File file = new File("D:\\java eclipse\\eclipse-workspace\\Counter\\src\\news.txt");
List<String> lists = new ArrayList<String>(txt2String(file));
count(lists);
}
}
運行結果如下:
如有錯誤,敬請指正。
北大青鳥APTECH成立于1999年。依托北京大學優(yōu)質(zhì)雄厚的教育資源和背景,秉承“教育改變生活”的發(fā)展理念,致力于培養(yǎng)中國IT技能型緊缺人才,是大數(shù)據(jù)專業(yè)的國家
達內(nèi)教育集團成立于2002年,是一家由留學海歸創(chuàng)辦的高端職業(yè)教育培訓機構,是中國一站式人才培養(yǎng)平臺、一站式人才輸送平臺。2014年4月3日在美國成功上市,融資1
北大課工場是北京大學校辦產(chǎn)業(yè)為響應國家深化產(chǎn)教融合/校企合作的政策,積極推進“中國制造2025”,實現(xiàn)中華民族偉大復興的升級產(chǎn)業(yè)鏈。利用北京大學優(yōu)質(zhì)教育資源及背
博為峰,中國職業(yè)人才培訓領域的先行者
曾工作于聯(lián)想擔任系統(tǒng)開發(fā)工程師,曾在博彥科技股份有限公司擔任項目經(jīng)理從事移動互聯(lián)網(wǎng)管理及研發(fā)工作,曾創(chuàng)辦藍懿科技有限責任公司從事總經(jīng)理職務負責iOS教學及管理工作。
浪潮集團項目經(jīng)理。精通Java與.NET 技術, 熟練的跨平臺面向對象開發(fā)經(jīng)驗,技術功底深厚。 授課風格 授課風格清新自然、條理清晰、主次分明、重點難點突出、引人入勝。
精通HTML5和CSS3;Javascript及主流js庫,具有快速界面開發(fā)的能力,對瀏覽器兼容性、前端性能優(yōu)化等有深入理解。精通網(wǎng)頁制作和網(wǎng)頁游戲開發(fā)。
具有10 年的Java 企業(yè)應用開發(fā)經(jīng)驗。曾經(jīng)歷任德國Software AG 技術顧問,美國Dachieve 系統(tǒng)架構師,美國AngelEngineers Inc. 系統(tǒng)架構師。