テキストの文字、単語数の統計

12787 ワード

テキスト操作は最も一般的で、例の形式でドライバの作成を駆動します.
例1:文章やコンピュータファイルの文字や単語の数を統計する
#-*-encoding:utf-8-*-

import time



keep = {'a','b','c','d','e','f','g','h','i','j','k',

     'l','m','n','o','p','q','r','s','t','u','v',

     'w','x','y','z',' ','-',"'"}





def normalize(s):

#       ,                  ,       

    result = ''

    for c in s.lower():

        if c in keep:

            result +=c

    return result    

    

def make_freq_dict(s):

    #

    s = normalize(s)

    words = s.split()

    d = {}

    for w in words: 

        if w in d:

            d[w] +=1

        else:

            d[w] = 1

            

    return d

        

def print_file_stats(fname):

    s = open(fname,'r').read()

    num_chars = len(s)

    num_lines = s.count('
') d = make_freq_dict(s) # num_words = sum(d[w] for w in d) lst = [(d[w],w) for w in d] lst.sort() lst.reverse() print("The file '%s' has: " % fname) print(" %s characters " % num_chars) print(" %s lines " % num_lines) print(" %s words" % num_words) print("
The top 10 most frequent words are:
") i=1 for count,word in lst[:10]:# print('%2s. %4s %s' % (i,count,word)) i +=1 def main(): start = time.time() print_file_stats('bill.txt') end = time.time() use = end - start print(' %s ' % use) if __name__=='__main__': main()

正規表現が使用されていないバージョン
例2:前に書いたC言語バージョンについて、単語数を統計する
#include "stdio.h"  

int count_word(char *str); 

void main()

{ 

   char str1[80];

   int sum=0;  

   puts("please enter a string");

   gets(str1); 

   sum=count_word(str1); //   count  sum 

   printf("there are %d words in this sentence",sum);

 } 

  int count_word(char *str)

 { 

    int count,flag; 

    char *p; 

    count=0;

     flag=0; 

     p=str; 

      while(*p!='\0')/**/

       { 

        if(*p==' ')/*         ,  flag  ,            */ 

        flag=0; 

        else if(flag==0)/*         ,  flag 0,      1,              */

         { 

          flag=1;/* flag   1,                      ,       ,   */ 

          count++; //count          。             ,            

          }

      p++; //         flag=0,    。          。              ,     。 

         } 

     return count;

 }