JAVA.使用FileReader字符流统计一篇英文中的单词,要求如下
①一共出现了多少个单词;②有多少个互不相同的单词;③给出每个单词出现的频率,并将这些单词按频率大小顺序输出到文件words.txt文件中。...
①一共出现了多少个单词;②有多少个互不相同的单词;③给出每个单词出现的频率,并将这些单词按频率大小顺序输出到文件words.txt文件中。
展开
2个回答
展开全部
我已经给你写好了,你要求的功能都能实现,以下是源代码:
package regular;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
/**
* 统计一篇英文中的单词,要求如下:
* ①一共出现了多少个单词;②有多少个互不相同的单词;③给出每个单词出现的频率,并将这些单词按频率大小顺序输出到文件words.txt文件中。
* */
public class WordStatistics {
private BufferedReader bufferedReader = null;
private BufferedWriter bufferedWriter = null;
public static void main(String[] args) {
WordStatistics wordStatistics = new WordStatistics();
Map<String, Integer> word_map = wordStatistics.readFile();
// for(Map.Entry<String, Integer> mapping : word_map.entrySet()){
// System.out.println(mapping.getKey() + " : " + mapping.getValue());
// }
wordStatistics.sortAndWrite(word_map);
}
/**
* 从指定路径读取英文文章,并形成Map集合
* */
public Map<String, Integer> readFile(){
//读文件
StringBuffer stringBuffer = new StringBuffer();
try {
bufferedReader = new BufferedReader(new FileReader(new File("F:\\text1.txt"))); //文件路径可自定义
String line = "";
while((line = bufferedReader.readLine()) != null)
stringBuffer.append(line);
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//生成<单词,次数>键值对
Pattern pattern = Pattern.compile("(\\.)? ");
String[] words = pattern.split(stringBuffer.toString());
Map<String, Integer> word_map = new HashMap<String, Integer>();
for(String s : words){
if(!word_map.containsKey(s)){
word_map.put(s, 1);
}
else{
int count = word_map.get(s);
word_map.replace(s, count, count+1);
}
}
return word_map;
}
/**
* 按单词的出现频率排序并输出到words.txt文件中
* */
public void sortAndWrite(Map<String, Integer> word_map){
//排序
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(word_map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2) {
// TODO Auto-generated method stub
return o1.getValue().compareTo(o2.getValue());
}
});
//写入文件
try {
bufferedWriter = new BufferedWriter(new FileWriter(new File("F:\\words.txt")));
bufferedWriter.write("一共出现了 " + word_map.size() + " 个单词,每个单词和它出现的频率分别是:");
bufferedWriter.flush();
bufferedWriter.newLine();
for(Map.Entry<String, Integer> mapping : list){
bufferedWriter.write(mapping.getKey() + " : " + mapping.getValue());
bufferedWriter.flush();
bufferedWriter.newLine();
}
bufferedWriter.close();
System.out.println("Work Out");
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试用例:
She had been shopping with her Mom in Wal-Mart. She must have been 6 years old, this beautiful brown haired, freckle-faced image of innocence. It was pouring outside. The kind of rain that gushes over the top of rain gutters, so much in a hurry to hit the Earth, it has no time to flow down the spout.
输出:
(PS:这可全部是原创手写的,望采纳)
追问
word_map.replace(s, count, count+1);这是什么
展开全部
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
* 2015年11月28日下午10:40:03
*
* @author hp TODO 练习文件操作
*
*/
public class CountWord {
private RandomAccessFile accessFile;
private Map<String, Integer> treeMap = new TreeMap<String, Integer>();
/**
* 按照文件名获取RandomAccessFile对象
*
* @param fileName
* 文件名
* @return
*/
public RandomAccessFile getRandomAccessFileByFileName(String fileName) {
try {
return new RandomAccessFile(fileName, "rw");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* 显示Map里面的值
*/
public void displayMap() {
Iterator<String> it = treeMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
System.out.println(key + " " + treeMap.get(key));
}
}
/**
* 将元素放进Map
*
* @param words
* 元素数组
*/
public void putIntoMap(String[] words) {
for (int index = 0; null != words && index < words.length; index++) {
treeMap.put(words[index], treeMap.get(words[index]) == null ? 1 : treeMap.get(words[index]) + 1);
}
}
/**
* 将字符串写入文件(尚未实现排序)
*
* @param fileName
* 文件名
*/
public void writerToFile(String fileName) {
try {
accessFile = getRandomAccessFileByFileName(fileName);
Iterator<String> it = treeMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
accessFile.write((key + "\r\n").getBytes());
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println("---Finish writer to: " + fileName + "----");
}
/**
* 计算文件有多少个单词
*
* @param fileName
* 文件名
* @return
*/
public int countWords(String fileName) {
try {
accessFile = getRandomAccessFileByFileName(fileName);
int total = 0;
String line = "";
while (null != (line = accessFile.readLine())) {
String[] words = line.split(" ");// 默认空格隔开为一个单词
putIntoMap(words);
total += words.length;
}
return total;
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public static void main(String[] args) {
CountWord cw = new CountWord();
String fileName = "D://word.txt";
String saveFile = "D://words.txt";
System.out.println("\nTotal words: " + cw.countWords(fileName) + "\n\n");
System.out.println("--------- Words And Times ----------");
cw.displayMap();
System.out.println("--------- Writer to File ----------");
cw.writerToFile(saveFile);
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询