- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您如何评价以下任务的解决方案的结构、正确性、简单性、可测试性(任务时间约 1 小时):
Create a command-line Java program that counts unique words from a text file and lists the top 10 occurrences.
English locale and treating hyphen and apostrophe as part of a word, output should look like the following:
and (514)
the (513)
i (446)
to (324)
a (310)
of (295)
my (288)
you (211)
that (188)
this (185)
解决方案:
WordCalculator.java(主类)
public class WordCalculator {
/**
* Counts unique words from a text file and lists the top 10 occurrences.
*
* @param args the command line arguments. First argument is the file path.
* If omitted, user will be prompted to specify path.
*
* @throws java.io.FileNotFoundException if the file for some other reason
* cannot be opened for reading.
*
* @throws java.io.IOException If an I/O error occurs
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
File file;
List<String> listOfWords = new ArrayList<>();
// If a command argument is specified, use it as the file path.
// Otherwise prompt user for the path.
if (args.length > 0) {
file = new File(args[0]);
} else {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter path to file: ");
file = new File(scanner.nextLine());
}
// Reads the file and splits the input into a list of words
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
listOfWords.addAll(WordUtil.getWordsFromString(line));
}
} catch (FileNotFoundException ex) {
Logger.getLogger(WordCalculator.class.getName()).log(Level.SEVERE,
String.format("Access denied reading from file '%s'.", file.getAbsolutePath()), ex);
throw ex;
} catch (IOException ex) {
Logger.getLogger(WordCalculator.class.getName()).log(Level.SEVERE,
"I/O error while reading input file.", ex);
throw ex;
}
// Retrieves the top ten frequent words and their frequencies.
Map<Object, Long> freqMap = FrequencyUtil.getItemFrequencies(listOfWords);
List<Map.Entry<?, Long>> topTenWords = FrequencyUtil.limitFrequency(freqMap, 10);
// Prints the top ten words and their frequencies.
topTenWords.forEach((word) -> {
System.out.printf("%s (%d)\r\n", word.getKey(), word.getValue());
});
}
}
FrequencyUtil.java
public class FrequencyUtil {
/**
* Transforms a list into a map with elements and their frequencies.
*
* @param list, the list to parse
* @return the item-frequency map.
*/
public static Map<Object, Long> getItemFrequencies(List<?> list) {
return list.stream()
.collect(Collectors.groupingBy(obj -> obj,Collectors.counting()));
}
/**
* Sorts a frequency map in descending order and limits the list.
*
* @param objFreq the map elements and their frequencies.
* @param limit the limit of the returning list
* @return a list with the top frequent words
*/
public static List<Map.Entry<?, Long>> limitFrequency(Map<?, Long> objFreq, int limit) {
return objFreq.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.limit(limit)
.collect(Collectors.toList());
}
}
WordUtil.java
public class WordUtil {
public static final Pattern ENGLISH_WORD_PATTERN = Pattern.compile("[A-Za-z'\\-]+");
/**
*
* @param s the string to parse into a list of words. Words not matching the
* english pattern(a-z A-z ' -) will be omitted.
*
* @return a list of the words
*
*/
public static List<String> getWordsFromString(String s) {
ArrayList<String> list = new ArrayList<>();
Matcher matcher = ENGLISH_WORD_PATTERN.matcher(s);
while (matcher.find()) {
list.add(matcher.group().toLowerCase());
}
return list;
}
}
最佳答案
您的解决方案是正确的,但如果您正在寻找功能较少的编程解决方案和更多的 OOP。您应该避免将 Utils 类与静态方法一起使用。您可以使用 WordCalculator 添加实例方法和属性作为计数单词的映射。此外,正则表达式模式对性能操作来说很重,并且您正在执行循环(以功能方式)将此分割的单词添加到 map 中。其他选项是逐字节读取文件,当您发现非字母字符(文本文件很简单就足以检查空格)时,将单词从 StringBuilder 转储到映射中,并向计数器添加 1。这样,如果文件是一个巨大的单行文本,您还可以避免可能出现的问题。
private void readWords(File file) {
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
StringBuilder build = new StringBuilder();
int value;
while ((value = bufferedReader.read()) != -1) {
if(Character.isLetterOrDigit(value)){
build.append((char)Character.toLowerCase(value));
} else {
if(build.length()>0) {
addtoWordMap(build.toString());
build = new StringBuilder();
}
}
}
if(build.length()>0) {
addtoWordMap(build.toString());
}
} catch(FileNotFoundException e) {
//todo manage exception
e.printStackTrace();
} catch (IOException e) {
//todo manage exception
e.printStackTrace();
}
}
关于java - 您如何评价以下 java 解决方案或者您将如何解决它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45695374/
Confusion rose because of this post. The author updated his post, and the result became clear. Concl
假设我有以下语句: bool foo=true; if (foo){ foo=false; } else{ //do
关闭。这个问题是opinion-based .它目前不接受答案。 想要改进这个问题? 更新问题,以便 editing this post 可以用事实和引用来回答它. 关闭 9 年前。 Improve
我有一个表单,其中有很多设置页面。所有的页面都是一样的,所以我宁愿只制作一个表格,然后传入它应该编辑的设置的名称。我该怎么做?假设该表单称为“ConfigForm”,我希望能够用这样的方式调用它: n
简单问题: 我通过 javascript 使用 Youtube gdata 来:评论、回复和喜欢/不喜欢视频。到目前为止一切正常! 但是,我正在尝试允许用户特别喜欢和不喜欢评论(就像在本地 youtu
我在设置 TableView 中有一个单元格,我想将用户直接发送到 Appstore 并打开应用程序页面,以便他们可以发表评论。在 Stackoverflow 中有很多关于此的内容,但在 iOS8 和
快速提问 - 如标题所述。那可能吗?我认为以下端点是我最好的选择:https://developers.google.com/youtube/v3/docs/comments/update ,但找不到
我是一名优秀的程序员,十分优秀!