導入Java . util . collections;
導入Java . util . comparator;
導入Java . util . iterator;
導入Java . util . list;
導入Java . util . set;
導入Java . util . treeset;
公共類文章{
//保存文章內容
字符串內容;
string[]raw words;
String[]單詞;
int[]wordFreqs;
公共文章(){
content =
}
public void splitWord() {
最終字符空間=“”;
content = content.replace('\ ' ',空格)。替換(',',空格)
。替換(' . '),空格);
content = content.replace(',空格)。替換(')',空格)
。替換('-',空格);
raw words = content . split(" \ \ s+");
}
public void countWordFreq() {
設置& lt字符串& gtset =新樹集& lt字符串& gt();
for (String word : rawWords) {
set . add(word);
}
叠代器ite = set . iterator();
列表& lt字符串& gtwordsList = new ArrayList & lt字符串& gt();
列表& lt整數& gtfreqList = new ArrayList & lt整數& gt();
while (ite.hasNext()) {
String word =(String)ite . next();
int count = 0;
for (String str : rawWords) {
if (str.equals(word)) {
count++;
}
}
words list . add(word);
freq list . add(count++);
}
words = wordsList.toArray(新字符串[0]);
wordFreqs = new int[freq list . size()];
for(int I = 0;我& ltfreq list . size();i++) {
wordFreqs[I]= freq list . get(I);
}
}
公共void排序(){
類別詞{
私有字符串字;
私有int freq
public Word(String word,int freq) {
this.word = word
this.freq = freq
}
}
WordComparator類實現比較器{
public int compare(Object o 1,Object o2) {
Word Word 1 =(Word)o 1;
Word Word 2 =(Word)O2;
if(word 1 . freq & lt;word2.freq) {
返回1;
} else if(word 1 . freq & gt;word2.freq) {
return-1;
}否則{
int len 1 = word 1 . word . trim()。長度();
int len2 = word2.word.trim()。長度();
string min = len 1 & gt;len2?word 2 . word:word 1 . word;
string max = len 1 & gt;len2?word 1 . word:word 2 . word;
for(int I = 0;我& lt最小長度();i++) {
if(min . charat(I)& lt;最大charAt(i)) {
返回1;
}
}
返回1;
}
}
}
List wordList = new ArrayList & ltWord & gt();
for(int I = 0;我& ltwords.lengthi++) {
wordList.add(new Word(words[i],wordFreqs[I]);
}
Collections.sort(wordList,new word comparator());
for(int I = 0;我& ltword list . size();i++) {
Word wor =(Word)Word list . get(I);
words[I]= wor . word;
wordFreqs[I]= wor . freq;
}
}
public void printResult() {
system . out . println(" Total "+words . length
+“內容用詞不同!”);
for(int I = 0;我& ltwords.lengthi++) {
system . out . println(wordFreqs[I]+" "+words[I]);
}
}
公共靜態void main(String[] args) {
文章a =新文章();
a . content = " sssssssssaadwerqwersssdfsdftrytyum 1242357689235 cvbbnm,masdfasdfasdfasdf,fasdf . asdfasdfasdfasdfaasdfasdf ";
a . split word();
a . count wordfreq();
a . sort();
a . print result();
}
}
運行壹下看是否成功,確實是分號錯了!現在已經改了!