- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我从编码站点获得了以下程序。
以下代码读取文本文件并查找重复的单词。
读取每个文本文件并逐行显示重复字数。以及如果文件未存储为字符串,如何调用该文件,我使用了缓冲读取器,但没有得到输出。
我的问题:
如何让程序从给定的文件夹中读取多个文件?
如何将结果保存为Excel文件格式?
欢迎提出任何建议。
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
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.Set;
import java.util.StringTokenizer;
import java.util.Map.Entry;
public class MaxDuplicateWordCount {
public Map<String, Integer> getWordCount(String fileName){
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
Map<String, Integer> wordMap = new HashMap<String, Integer>();
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while((line = br.readLine()) != null){
StringTokenizer st = new StringTokenizer(line, " ");
while(st.hasMoreTokens()){
String tmp = st.nextToken().toLowerCase();
if(wordMap.containsKey(tmp)){
wordMap.put(tmp, wordMap.get(tmp)+1);
} else {
wordMap.put(tmp, 1);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try{if(br != null) br.close();}catch(Exception ex){}
}
return wordMap;
}
public List<Entry<String, Integer>> sortByValue(Map<String, Integer> wordMap){
Set<Entry<String, Integer>> set = wordMap.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
{
public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
{
return (o2.getValue()).compareTo( o1.getValue() );
}
} );
return list;
}
public static void main(String a[]){
MaxDuplicateWordCount mdc = new MaxDuplicateWordCount();
Map<String, Integer> wordMap = mdc.getWordCount("E:\\Blog 39.txt");
List<Entry<String, Integer>> list = mdc.sortByValue(wordMap);
for(Map.Entry<String, Integer> entry:list){
System.out.println(entry.getKey()+" ="+entry.getValue());
}
}
}
最佳答案
在与 OP 交谈后,以下是 OP 的简要要求:
1- 从特定文件夹读取文件,文件通常是 Unicode 文本文件。
2- 文件将在问题中的 OP 算法中处理,算法的结果应再次保存在 Unicode 文件中(后来 OP 要求保存为 Excel 文件(.XLS),因为 Unicode 与 Excel 兼容)
这可以通过以下步骤解决:
第 1 步我们定义(声明)我们的工作空间
第 2 步 如果不存在,我们在工作空间中创建输出文件夹
第 3 步 我们读取工作空间文件夹中的所有现有文件并在算法中处理它们。
第 4 步每个文件的结果将在输出文件夹中保存为 Excel 文件。
首先您需要导入 POI 包,这将允许您创建 XLS 表。我已经下载了这个poi/poi-3.5-FINAL.jar.zip( 1,372 k)并且应将以下导入添加到您的代码中。
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
接下来您将以下代码添加到您的代码中,它是 self 解释的代码:
final static String WORKSPACE = "C:/testfolder/";
private static void createOutputFolder(String outputFolderName) {
File outputDirectory = new File(WORKSPACE + outputFolderName);
if (!outputDirectory.exists()) {
try {
outputDirectory.mkdir();
} catch (Exception e) {
}
}
}
private static void exlCreator() {
String outputFolder = "output/";
String fileName, fileNameWPathInput;
int serialNumber = 1;
createOutputFolder(outputFolder);
MaxDuplicateWordCount mdc = new MaxDuplicateWordCount();
File folder = new File(WORKSPACE);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
fileName = listOfFiles[i].getName();
fileNameWPathInput = WORKSPACE + fileName;
Map<String, Integer> wordMap = mdc.getWordCount(fileNameWPathInput);
List<Entry<String, Integer>> list = mdc.sortByValue(wordMap);
String fileNameWPathOutput = WORKSPACE + outputFolder +
fileName.substring(0, fileName.length() - 4)
+ "output.xls";
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("ResultSheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell(0).setCellValue("Serial No.");
rowhead.createCell(1).setCellValue("Word");
rowhead.createCell(2).setCellValue("Count");
for (Map.Entry<String, Integer> entry : list) {
HSSFRow row = sheet.createRow((short) serialNumber);
row.createCell(0).setCellValue(serialNumber);
row.createCell(1).setCellValue(entry.getKey());
row.createCell(2).setCellValue(entry.getValue());
serialNumber++;
}
FileOutputStream fileOut = new FileOutputStream(fileNameWPathOutput);
workbook.write(fileOut);
fileOut.close();
serialNumber = 1;
System.out.println(fileNameWPathOutput + " is created");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
public static void main(String [] args) throws IOException {
exlCreator();
}
通过操作代码,可以创建一个输出文件,但在工作表中创建每个输出结果。如下图所示,输出文件在 Excel 中打开,显示 Unicode 文本没有问题,因为这是我第一个解决方案中的问题:
Download POI
POI documentation
Unicode problem in CSV
More about CSV
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
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.Set;
import java.util.StringTokenizer;
import java.util.Map.Entry;
//for Excel ark
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
public class MaxDuplicateWordCount {
public Map<String, Integer> getWordCount(String fileName) {
FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
Map<String, Integer> wordMap = new HashMap<String, Integer>();
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " ");
while (st.hasMoreTokens()) {
String tmp = st.nextToken().toLowerCase();
if (wordMap.containsKey(tmp)) {
wordMap.put(tmp, wordMap.get(tmp) + 1);
} else {
wordMap.put(tmp, 1);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (Exception ex) {
}
}
return wordMap;
}
public List<Entry<String, Integer>> sortByValue(Map<String, Integer> wordMap) {
Set<Entry<String, Integer>> set = wordMap.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
return list;
}
final static String WORKSPACE = "C:/testfolder/";
private static void createOutputFolder(String outputFolderName) {
File outputDirectory = new File(WORKSPACE + outputFolderName);
if (!outputDirectory.exists()) {
try {
outputDirectory.mkdir();
} catch (Exception e) {
}
}
}
private static void exlCreator() {
String outputFolder = "output/";
String fileName, fileNameWPathInput;
int serialNumber = 1;
createOutputFolder(outputFolder);
MaxDuplicateWordCount mdc = new MaxDuplicateWordCount();
File folder = new File(WORKSPACE);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
fileName = listOfFiles[i].getName();
fileNameWPathInput = WORKSPACE + fileName;
Map<String, Integer> wordMap = mdc.getWordCount(fileNameWPathInput);
List<Entry<String, Integer>> list = mdc.sortByValue(wordMap);
String fileNameWPathOutput = WORKSPACE + outputFolder +
fileName.substring(0, fileName.length() - 4)
+ "output.xls";
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("ResultSheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell(0).setCellValue("Serial No.");
rowhead.createCell(1).setCellValue("Word");
rowhead.createCell(2).setCellValue("Count");
for (Map.Entry<String, Integer> entry : list) {
HSSFRow row = sheet.createRow((short) serialNumber);
row.createCell(0).setCellValue(serialNumber);
row.createCell(1).setCellValue(entry.getKey());
row.createCell(2).setCellValue(entry.getValue());
serialNumber++;
}
FileOutputStream fileOut = new FileOutputStream(fileNameWPathOutput);
workbook.write(fileOut);
fileOut.close();
serialNumber = 1;
System.out.println(fileNameWPathOutput + " is created");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}
public static void main(String[] args) throws IOException {
exlCreator();
}
}
关于java - 如何从目录或文件夹中读取重复字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34894763/
嗨,我是excel的初学者,所以请原谅我的无知。 最近我发现自己需要一个函数来计算一系列单元格中的单词数(当然,将空单元格计为 0)。 在网上冲浪我发现了这个简单的 VBA 代码: Function
我是编程新手,这段代码不想工作,而且我已经没有想法了。它可以很好地读取文件,但不会计算任何内容。我知道它与 while 语句有关。这是针对两个单独的文件,但它们都需要显示在末尾。 #define _C
我用 Java 实现了一个字数统计程序。基本上,该程序需要一个大文件(在我的测试中,我使用了一个仅包含数字的 10 GB 数据文件),并计算每个“单词”出现的次数 - 在这种情况下,一个数字(例如 2
长话短说:1986 年,一位面试官要求 Donald Knuth 编写一个程序,输入文本和数字 N,并列出按频率排序的 N 个最常用的词。 Knuth 编写了一个 10 页的 Pascal 程序,Do
我有一个包含 2 个字段的表: cnt str -- ------- 60 the 58 of 4 no 30 the 2 of 1 no 我想要这样的结果 cnt
各位seoer应该都明白,要想网站有排名,收录是前提条件,没有收录完全谈不上排名、流量。但是内页的收录往往是seo最大的难题之一,笔者手上有一堆网站都是只被收录了首页或者几页内页,因此解决内页收录问
是否可以设置一个 checkstyle 规则来计算评论中的字数,然后在字数低于定义的限制时显示问题。我在checkstyle上搜索了Javadoc属性,但没有发现有用的东西。 例如: /** * S
我有一个名为“input.txt”的文本文件,其中包含: test line one test line two final line 编译并运行后通过 $ ./a.exe #include
我目前在带有 pandas 0.23.4 的 Jupyter Notebook (v5.6.0) 中使用 python3.7。 我编写了代码来标记一些日语单词,并成功应用了一个字数统计函数,该函数返回
我刚刚用出色的 Redactor 替换了 CKEditor(它伴随着大量与 AJAX 更新 DOM 相关的神秘问题) .我们以前使用 CKEditor 插件为我们提供富文本编辑器的字符数。我怎样才能用
我想在 Eclipse 集群上运行 hadoop 字数统计。但我收到错误。我更改了输出目录,但程序行为没有变化。你能帮我解决这个错误吗: 2013-10-23 23:06:13,783 WA
我正在尝试运行一个 wordcount 程序,但我收到以下代码的错误 job.setInputFormatClass(TextInputFormat.class); job.setOutputForm
这是 Hadoop 字数统计 java map 和 reduce 源代码: 在 map 函数中,我已经可以输出所有以字母“c”开头的单词以及该单词出现的总次数,但我想做的只是输出以字母“c”开头的单词
我是一名优秀的程序员,十分优秀!