2

(is、are、am、was など) のような一般的な単語をテキスト ファイルから削除する必要があります。Javaでそれを行う効率的な方法は何ですか?

4

1 に答える 1

4

削除する単語をスキップしてファイルを読み込み、ファイルを書き戻す必要があります。

このため、ユースケースによっては、読むたびに無視したい単語をスキップすることをお勧めします。

実際に単語を行ごとに削除するには(とにかくそれを実行したい方法ではない可能性があります)、これを行うことができます(google guavaを使用):

    // the words you want to remove from the file:
    //
    Set<String> wordsToRemove = ImmutableSet.of("a", "for");

    // this code will run in a loop reading one line after another from the file
    //
    String line = "Some words read from a file for example";
    StringBuffer outputLine = new StringBuffer();
    for (String word : Splitter.on(Pattern.compile("\\s+")).trimResults().omitEmptyStrings().split(line)) {
        if (!wordsToRemove.contains(word)) {
            if (outputLine.length() > 0) {
                outputLine.append(' ');
            }
            outputLine.append(word);
        }
    }

    // here I'm just printing, but this line could now be written to the output file.
    //
    System.out.println(outputLine.toString());

このコードを実行すると、次のように出力されます。

Some words read from file example

つまり、「a」と「for」は省略されます。

これは単純なコードになりますが、ファイルの空白のフォーマットが変更されることに注意してください。スペースやタブなどが2倍になった行がある場合、このコードではこれがすべて1つのスペースに変更されます。これは、要件に応じて、おそらくより良い方法があるでしょう。

于 2012-04-20T10:18:11.297 に答える