编写一个字符统计程序编程,详见教材第一章。实现以下功能
a) 从指定的文本文件中读取文本信息;
b) 将除去标点符号外的单词进行统计;
c) 统计的单词不区分大小写(选做);
d) 统计结果包含单词名称及在文本中出现的次数
e) 统计结果结束输出到控制台屏幕;
f) 统计结果输出到指定的统计文件中;
g) 统计结果按字母顺序排列。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
namespace WordCount
{
class EntryPoint
{
[STAThread]
public static void Main(string[] args)
{
string text_line;
string file_name;
if (args.Length == 0) { display_usage(); return; }
else
{
foreach (string option in args) Console.WriteLine(option);//输出用户输入的参数
foreach (string option in args)
{
if (option.Equals("-h")) { display_usage(); return; }//显示该程序用法
else //check_valid_file_type(option);//检查可用文件类型
{
file_name = option;
StreamReader freader = File.OpenText(file_name);
StreamWriter fwriter = File.CreateText(@"C:/mytext.txt");
ArrayList text = new ArrayList();
while ((text_line = freader.ReadLine()) != null)
{
if (text_line.Length == 0)
continue;
text.Add(text_line);//对ArrayList末尾插入新元素
}
string[][] sentences;
sentences = new string[text.Count][];//sentences是数组,以string为元素
string str;
for (int ix = 0; ix < text.Count; ++ix)
{
str = (string)text[ix];
sentences[ix] = str.Split(null);
}
int diml_length = sentences.GetLength(0);
Console.WriteLine("There are {0} arrays stored in sentences", diml_length);
for (int ix = 0; ix < diml_length; ++ix)
{
Console.WriteLine("There are {0} words in array {1}", sentences[ix].Length, ix + 1);
foreach (string s in sentences[ix]) ;
}
Hashtable words = new Hashtable();
diml_length = sentences.GetLength(0);
for (int ix = 0; ix < diml_length; ++ix)
{
foreach (string st in sentences[ix])
{
string key = st.ToLower();
if (!words.Contains(key))
words.Add(key, 1);//等同于words[key]=1;
else
words[key] = (int)words[key] + 1;//统计相同单词的个数
}
}
foreach (DictionaryEntry de in words) ;
ArrayList aKeys = new ArrayList(words.Keys);
aKeys.Sort();
foreach (string key in aKeys)
fwriter.WriteLine("{0}::{1}", key, words[key]);
freader.Close();//释放占用相关资源
fwriter.Close();
}
}
}
}
public static void display_usage()
{
string usage = @"usage:WordCount [-s] [-t] [-h] textfile.txt
where [] indicates an optional argument
-h prints this message";
Console.WriteLine(usage);
}
}
}