Java语言程序设计:编写Java程序统计一篇英文文档中各单词出现的次数,并按单词出现的频率由高到低进行输出。

目录

题目描述

思路分析

关于split()的更新补充

完整代码

运行测试

输入样例

 输出结果


修改更新声明

经过几天的学习,对之前的一些细节进行了修改。。。

题目描述

编写Java程序统计一篇英文文档中各单词出现的次数,并按单词出现的频率由高到低进行输出。

例如:文档“Hello word Hello”的统计结果为:

 Hello:2次

 word:1次

思路分析

  1. 1. 处理文档:先用nextLine()将文段输入,存储在字符串file,再调用split()方法将字符串分割成一个个单词放在一个数组中。
  2. 关于split()方法:
  3. 签名为:string.split("character"),其中,string为字符串类型变量实例,character为要设为分割符的字符。
  4. 连接符:若需要设置多个分割符,则需要用连接符 '|',将多个分割符连接起来。
  5. 特殊处理:如 ",:,.,\等符号是正则表达式的一部分,需要加反斜杠符"\"进行转义。
  6. 下面是本题的例子:
  7. String file = input.nextLine();//输入文档
    String[] words;
    words = file.split(" |,|\\.|\"");//设置字符串数组元素之间的分隔符,
    											//其中.和"是正则表达式的一部分,需要加进行转义
    								//通过实践发现两者进行转义的方法不同,分别是加“\\”和“\"
    关于split()的更新补充
  8. 后来学习发现,在设置多个分隔符时,可以采用以下方法:
  9. 用中括号 ''[]'' 将多个要设置的分隔符包起来
  10. string.split("[ .,/"]");//其中"还是要加反斜杠"/"进行转义

  11. 2.设计一个方法实现输入一个有多个分段的短文
  12. //输入短文方法,可以满足输入含有分段的短文
    public static StringBuilder inputArticle(StringBuilder scanner) {
    	Scanner input = new Scanner(System.in);
    	//当下一行不为空时
    	while(input.hasNextLine()) {   
    		String paragraph = input.nextLine();//一段一段地输入
    		if(paragraph.equals("end")) //输入截止标志
    			break;
    		else 
    			scanner.append(paragraph);//将剩余字符追加到后面
    	}
    	return scanner;
    }
  13. 3.用for-each循环遍历数组将各个单词以及频次作为哈希表的条目存入自定义哈希表wordMap。
//for-each循环遍历							
for(String word: words) {
    if(word == "") continue;//处理空字符
    //将所有单词统一转换成小写,防止一个单词因为大小写不同原因被记为两个单词
    word = word.toLowerCase();
    //该位置哈希值为空值时,赋初始值1
    if(wordMap.get(word) == null)
	wordMap.put(word, 1);
	//哈希表位置不为空时,单词频次加一
	else 
		wordMap.put(word, wordMap.get(word) + 1);
}

4.排序:将Map的条目转换成List列表集合,调用Collection类中的sort方法进行排序。根据哈希值进行排序,需要重写比较器Comparator。

/*进行排序*/
//将Map的条目转换成List列表集合,调用Collection类中的sort方法进行排序
ArrayList<Map.Entry<String, Integer>> wordNumberList = new ArrayList<>(wordMap.entrySet());
//根据值进行排序,需要重写比较器
Collections.sort(wordNumberList, new Comparator<Map.Entry<String, Integer>>(){
		@Override
		public int compare(Map.Entry<String, Integer> object1, Map.Entry<String, Integer> object2) {
			//降序
			return object2.getValue() - object1.getValue();
		}
});

5.打印结果:设置一个计数器count,每输出5个单词换行。

/*打印结果*/
int count = 0;//计数器
for(Map.Entry<String, Integer> entry: wordNumberList) {
	count++;
	System.out.print(entry.getKey() + ": " + entry.getValue() + "次  ");
	//每5个单词换行显示
	if(count % 5 == 0)
		System.out.printf("\n");
}

完整代码

import java.util.Scanner;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.lang.StringBuilder;

public class WordNumber {

	public static void main(String[] args) {
		HashMap<String, Integer> wordMap = new HashMap<>();//声明哈希表
		Scanner input = new Scanner(System.in);
		StringBuilder scanner = new StringBuilder();//定义一个字符串构建器,其长度可变
		System.out.println("请输入有一篇英语文档,以'end'标志结束:");
		scanner = inputArticle(scanner);//调用方法输入短文
		String file = scanner.toString();//将整个字符串赋值给file
		String[] words;
		words = file.split("[ .,\"]");//设置字符串数组元素之间的分隔符,
									//其中"是正则表达式的一部分,需要加进行转义
		//for-each循环遍历			//加“\"
		for(String word: words) {
			if(word == "") continue;//处理空字符
			//将所有单词统一转换成小写,防止一个单词因为大小写不同原因被记为两个单词
			word = word.toLowerCase();
			//该位置哈希值为空值时,赋初始值1
			if(wordMap.get(word) == null)
				wordMap.put(word, 1);
			//哈希表位置不为空时,单词频次加一
			else 
				wordMap.put(word, wordMap.get(word) + 1);
		}
		
		/*进行排序*/
		//将Map的条目转换成List列表集合,调用Collection类中的sort方法进行排序
		ArrayList<Map.Entry<String, Integer>> wordNumberList = new ArrayList<>(wordMap.entrySet());
		//根据值进行排序,需要重写比较器
		Collections.sort(wordNumberList, new Comparator<Map.Entry<String, Integer>>(){
			@Override
			public int compare(Map.Entry<String, Integer> object1, Map.Entry<String, Integer> object2) {
				//降序
				return object2.getValue() - object1.getValue();
			}
		});
		
		/*打印结果*/
		int count = 0;//计数器
		for(Map.Entry<String, Integer> entry: wordNumberList) {
			count++;
			System.out.print(entry.getKey() + ": " + entry.getValue() + "次  ");
			//每5个单词换行显示
			if(count % 5 == 0)
				System.out.printf("\n");
		}
	}
	//输入短文方法,可以满足输入含有分段的短文
	public static StringBuilder inputArticle(StringBuilder scanner) {
		Scanner input = new Scanner(System.in);
		//当下一行不为空时
		while(input.hasNextLine()) {   
			String paragraph = input.nextLine();//一段一段地输入
			if(paragraph.equals("end")) //输入截止标志
				break;
			else 
				scanner.append(paragraph);//将剩余字符追加到后面
		}
		return scanner;
	}
}

运行测试

输入样例

英文文档《I have a dream》前五段

I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of bad captivity.
But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself an exile in his own land. And so we've come here today to dramatize a shameful condition.
In a sense we've come to our nation's capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir. This note was a promise that all men, yes, black men as well as white men, would be guaranteed the "unalienable Rights" of "Life, Liberty and the pursuit of Happiness." It is obvious today that America has defaulted on this promissory note, insofar as her citizens of color are concerned. Instead of honoring this sacred obligation, America has given the Negro people a bad check, a check which has come back marked "insufficient funds."
But we refuse to believe that the bank of justice is bankrupt. We refuse to believe that there are insufficient funds in the great vaults of opportunity of this nation. And so, we've come to cash this check, a check that will give us upon demand the riches of freedom and the security of justice.
end
 输出结果
the: 25次  of: 24次  a: 11次  to: 11次  in: 10次  
and: 7次  as: 6次  this: 6次  negro: 6次  years: 5次  
is: 5次  that: 5次  check: 5次  come: 4次  hundred: 4次  
one: 4次  later: 4次  today: 4次  still: 3次  we've: 3次  
our: 3次  has: 3次  we: 3次  men: 3次  bad: 2次  
nation: 2次  american: 2次  america: 2次  cash: 2次  it: 2次  
believe: 2次  refuse: 2次  freedom: 2次  are: 2次  came: 2次  
so: 2次  great: 2次  but: 2次  justice: 2次  funds: 2次  
which: 2次  insufficient: 2次  history: 2次  note: 2次  life: 2次  
on: 2次  will: 2次  was: 2次  been: 1次  a great american: 1次  
injustice: 1次  shadow: 1次  chains: 1次  happy: 1次  ago: 1次  
hope: 1次  when: 1次  score: 1次  bank: 1次  proclamation: 1次  
finds: 1次  would: 1次  her: 1次  liberty: 1次  seared: 1次  
join: 1次  poverty: 1次  lonely: 1次  you: 1次  they: 1次  
symbolic: 1次  slaves: 1次  give: 1次  lives: 1次  momentous: 1次  
night: 1次  signed: 1次  opportunity: 1次  sense: 1次  am: 1次  
unalienable: 1次  whose: 1次  an: 1次  demand: 1次  decree: 1次  
himself: 1次  light: 1次  millions: 1次  demonstration: 1次  be: 1次  
languished: 1次  pursuit: 1次  magnificent: 1次  long: 1次  corners: 1次  
fall: 1次  crippled: 1次  by: 1次  rights: 1次  nation's: 1次  
stand: 1次  free: 1次  sacred: 1次  sadly: 1次  words: 1次  
black: 1次  vaults: 1次  i: 1次  honoring: 1次  declaration: 1次  
people: 1次  obvious: 1次  vast: 1次  signing: 1次  citizens: 1次  
capital: 1次  concerned: 1次  republic: 1次  own: 1次  had: 1次  
promise: 1次  dramatize: 1次  independence: 1次  upon: 1次  down: 1次  
flames: 1次  his: 1次  white: 1次  midst: 1次  discrimination: 1次  
segregation: 1次  five: 1次  insofar: 1次  us: 1次  emancipation: 1次  
all: 1次  marked: 1次  given: 1次  daybreak: 1次  island: 1次  
wrote: 1次  guaranteed: 1次  a promissory note: 1次  condition: 1次  beacon: 1次  
ocean: 1次  withering: 1次  architects: 1次  were: 1次  obligation: 1次  
who: 1次  here: 1次  constitution: 1次  color: 1次  for: 1次  
exile: 1次  manacles: 1次  back: 1次  captivity: 1次  joyous: 1次  
not: 1次  society: 1次  security: 1次  happiness: 1次  heir: 1次  
promissory: 1次  defaulted: 1次  land: 1次  end: 1次  prosperity: 1次  
shameful: 1次  every: 1次  greatest: 1次  yes: 1次  go: 1次  
instead: 1次  with: 1次  what: 1次  material: 1次  riches: 1次  
there: 1次  well: 1次  bankrupt: 1次  

  • 19
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值