rss· 投稿· 设为首页· 加入收藏· 繁體版
当前位置: 火魔网 » 程序开发 » Java基础

JAVA编程:统计英文文本文件中的字符数目和单词数目

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;class TextStats extends JFrame {
    public static void main(String[] args) {
        new TextStats();
    }    public TextStats() {
        final TextArea text = new TextArea("", 40, 50, TextArea.SCROLLBARS_VERTICAL_ONLY),
                       stats = new TextArea(40, 50);        text.addTextListener(new TextListener() {
            public void textValueChanged(TextEvent e) {
                String[] words = text.getText().toLowerCase().split("[\\W&&[^'-]]+");
                Map<String, Integer> count = new TreeMap<String, Integer>();
                for (String word: words)
                    if (word.length() > 0)
                        count.put(word, count.containsKey(word) ? count.get(word) + 1 : 1);
                stats.setText(count.toString().replaceAll("[{}]|, ", "\n").trim());
            }
        });        add(text);
        add(stats, BorderLayout.EAST);
        stats.setEditable(false);        setTitle("单词排序与统计");
        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }
}
 

顶一下
(0)
踩一下
(0)