C # Count and sort Words in English text

Source: Internet
Author: User

 
The idea is as follows:
1. Use the Hashtable (efficient) set to record the number of times each word appears
2. Use ArrayList to sort Keys in Hashtable in alphabetical order.
3. sort by insert (stable)

Public void StatisticsWords (string path) {if (! File. Exists (path) {Console. WriteLine ("the File does not exist! "); Return;} Hashtable ht = new Hashtable (StringComparer. ordinalIgnoreCase); StreamReader sr = new StreamReader (path, System. text. encoding. UTF8); string line = sr. readLine (); string [] wordArr = null; int num = 0; while (line. length> 0) {// MatchCollection mc = Regex. matches (line, @ "\ B [a-z] +", RegexOptions. compiled | RegexOptions. ignoreCase); // foreach (Match m in mc) // {// if (ht. containsKey (m. value) // {// num = Convert. toInt32 (ht [m. value]) + 1; // ht [m. value] = num; //} // else // {// ht. add (m. value, 1); //} // line = sr. readLine (); wordArr = line. split (''); foreach (string s in wordArr) {if (s. length = 0) continue; // remove punctuation line = Regex. replace (line, @ "[\ p {P} *]", "", RegexOptions. compiled); // Add words to the hash table if (ht. containsKey (s) {num = Convert. toInt32 (ht [s]) + 1; ht [s] = num;} else {ht. add (s, 1) ;}} line = sr. readLine ();} ArrayList keysList = new ArrayList (ht. keys); // sort Keys in Hashtable in alphabetical order. sort (); // Sort by number of inserts [stable sorting], so the words with the same number of times are still in alphabetical order string tmp = String. empty; int valueTmp = 0; for (int I = 1; I <keysList. count; I ++) {tmp = keysList [I]. toString (); valueTmp = (int) ht [keysList [I]; // times int j = I; while (j> 0 & valueTmp> (int) ht [keysList [j-1]) {keysList [j] = keysList [j-1]; j --;} keysList [j] = tmp; // j = 0} // print out foreach (object item in keysList) {Console. writeLine (string) item + ":" + (string) ht [item]) ;}}

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.