文件的读写(Java实训)

文件的读写(Java实训)

实训目的:

字符串处理、文件读写、集合的应用

实训要求:

自己先准备一个txt文件,文档里存有一篇英语短文。先一行行读取文件中的内容,并将一行行短文中的标点符号替换成空格,然后以空格作为划分标准,统计整个txt文档中每个单词出现的次数。

在这里插入图片描述

先放出文档英语文章。
article.txt
It also means those reflections of the diamond cannot be replaced by any kind of light or reflection, because the untrue reflection will not be a real diamond, and will not be able to spread out its resplendent and meaningful reflection of love to people about whom I care.

FileRead.java

package program6;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;

public class FileRead {

	public static void main(String[] args) {
		HashMap<String,Integer> m=new HashMap<>();
		try {
			BufferedReader reader=new BufferedReader(new FileReader("article.txt"));
			String ss=null;			
			while((ss=reader.readLine())!=null) {
				String[] str=ss.trim().split("\\s+");
				for(int i=0;i<str.length;i++) {
					String word=str[i].trim();
					if(m.containsKey(word)) {
						m.put(word, m.get(word)+1);
					}else {
						m.put(word, 1);
					}
				}
			}
			int cnt=0;
			System.out.println("统计各单词个数为:");
			Set<String> st=m.keySet();
			for(String k:st) {
				if(k.hashCode()!=0){
					char[] str=k.toCharArray();
					for(int i=0;i<str.length;i++) {
						if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')) {
							System.out.print(str[i]);
						}
					}
					System.out.println("出现了"+m.get(k.trim())+"次");	
					cnt++;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

在这里插入图片描述

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值