【问题标题】:Word counter program not producing correct number of words字计数器程序没有产生正确的字数
【发布时间】:2015-10-28 19:24:30
【问题描述】:

我不熟悉从文件中读取文本。 我有一个任务,我需要打印文件中的单词数量。

我在 Mac OS 上使用以 .rtf 结尾的 TextEdit

当我运行以下程序时,即使文档为空,我也会得到输出 5。当我添加单词时,计数不会正确增加。

谢谢。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Analyze{ 


public static void main(String[] args) throws FileNotFoundException{
    Scanner console = new Scanner(System.in);
    int words = 0; 
    System.out.println("This is a word counter");
    System.out.println("File name");
    String filename = console.next();
    File name = new File(filename);

    Scanner int2 = new Scanner(name);

    while (int2.hasNext()) {
        String temp = int2.next();
        words++;
    }

    System.out.println(words);
    }
}

【问题讨论】:

标签: java file counter word


【解决方案1】:

问题是您正在读取一个 RTF 文件。

使用 TextEdit 生成的“空白”(如未输入文本)RTF 文件如下所示:

{\rtf1\ansi\ansicpg1252\cocoartf1404\cocoasubrtf130
{\fonttbl}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww10800\viewh8400\viewkind0
}

如你所见,五行对应5的输出。

要么在你的程序中解析 RTF,我怀疑你想要这样做,要么将 TextEdit 切换到纯文本模式。见here

【讨论】:

    【解决方案2】:

    您要计算的文件是 RTF 文件吗?它是否支持斜体、粗体、字体选择和类似的东西?在这种情况下,它可能包含一些数据,即使没有文本。您的程序不关心文件格式,因此它天真地将所有内容都读取为文本。

    尝试在您的文件上运行 odhexdump(不确定它们是否存在于 Mac OS X 上?)——它们会打印文件的确切字节。真正的空文件不应产生任何输出。

    如果您的计算机没有odhexdump 程序,您可以尝试cat。它不会将内容打印为数字,因此它不会提供 100% 准确的特殊字符视图,但它应该能够向您展示您的文件是否为空。

    【讨论】:

    • 可以确认 OS X 同时拥有odhexdump
    【解决方案3】:

    除了RTF-Problem,还要注意

    扫描器使用分隔符模式将其输入分解为标记,默认情况下匹配空格。

    与空格一样

    空白字符:[ \t\n\x0B\f\r]

    所以计数包括制表符、换行符等,而不仅仅是空格

    【讨论】:

      猜你喜欢
      • 2016-01-09
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 2018-06-04
      相关资源
      最近更新 更多