練習題 (12): Extract uppercase words from a file, extract unique words.
本題可以利用 Regex 類別擷取檔案中所有的單字,並將單字放進 .NET 的泛型 Hash Table:Dictionary 類別中計算單字與其出現次數。
測試檔案內容:
In this file, THERE ARE some UPPERCASE words.
And, There ARE some redundant WORDS IN the content:
foo bar foo CSHARP Dictionary CSHARP Firefox Opera IE
JUST FOR FUN.
|
程式碼:
-
using System;
-
using System.Collections.Generic;
-
using System.IO;
-
using System.Text.RegularExpressions;
-
namespace DictionaryTest
-
{
-
internal class Program
-
{
-
private static void Main( string [ ] args)
-
{
-
StreamReader sr = new StreamReader ( "in.txt" );
-
Dictionary<string, int> d = new Dictionary<string, int> ( );
-
while (sr.Peek ( ) != -1 )
-
{
-
string s = sr.ReadToEnd ( );
-
Regex r = new Regex ( @"(\w+)", RegexOptions. IgnoreCase );
-
Match m = r.Match (s);
-
while (m.Success )
-
{
-
Group g = m.Groups [ 1 ];
-
if (!d.ContainsKey (g.ToString ( ) ) )
-
{
-
d.Add (g.ToString ( ), 1 );
-
}
-
else
-
{
-
d[g.ToString ( ) ] += 1;
-
}
-
m = m.NextMatch ( );
-
}
-
}
-
Console.WriteLine ( "Uppercase words:" );
-
Dictionary<string, int>.KeyCollection kc = d.Keys;
-
foreach ( string s in kc)
-
{
-
if (Regex.IsMatch (s, @"^[A-Z]+$" ) )
-
{
-
Console.WriteLine (s);
-
}
-
}
-
Console.WriteLine ( "Unique words:" );
-
foreach (KeyValuePair<string, int> kvp in d)
-
{
-
if (kvp.Value == 1 )
-
{
-
Console.WriteLine (kvp.Key );
-
}
-
}
-
sr.Dispose ( );
-
}
-
}
-
}
|