Frequency statistics of words and phrases in English documents

Source: Internet
Author: User

First, the procedure analysis

1. read file to string in read-only mode

def process_file (path):     Try :         ' R '             as file:= file.read ()    except  IOError:        Print ("Read File error! " )        return  None    return text

2, the data cleaning string, return a dictionary

Import= re.sub ('[^a-za-z0-9n]', textstring). Lower () . Split ()

Use regular expressions to filter out special characters in the document, replace them all with spaces, and facilitate subsequent separation operations. (ignores case, so all lowercase letters are used)

  

  2.1, only consider the word frequency statistics

 for inch word_list:      if inch word_freq:           + = 1      else:           = 1

Determines whether the word in the word list is in the word frequency dictionary.

If the word is in the dictionary, the number of the word is added 1;

If the word is not in the dictionary, the word is the key and the assignment is 1, indicating that the word appears for the first time.

  2.2. Consider the frequency of words and phrases

    2.2.1, data structure

A phrase is made up of a word connection, a word that can form a phrase with the preceding words, or a phrase with the following words.

At the same time, a word may appear in the article multiple times, and the words and the front and back form a variety of different phrases.

This means that almost every word can be spread out one after the other, which is quite similar to the graph structure.

The selection of the graph structure is quite in agreement with the current problem. However, currently python does not have a known graph class for us to manipulate. (custom class is temporarily not considered)

So I thought of the tree structure, cut off the word forward divergence, only left backwards. At this point, the problem becomes the building of forests.

In Python, forests are relatively easy to express. Using a dictionary to place the root node of each tree, the dictionary sets the dictionary and forms the forest.

You may want to ask where the statistics for the words and phrases are placed. I use "value" as the key, the key value number such a structure is placed in the dictionary of the word.

For a sample dictionary sample see Sample.json

    2.2.2, specific processes

  

Take the index stop at 50, the phrase limit number of words is 3 for example:

(1) Look for the mother node in the root node of the tree and create the mother node if it is not found.

                " Mother " : {                    "Value": 1                }            

(2) Look for the your node in the root node of the tree, find the mother node to continue looking for, and create a mother node. (cannot be found because the index must exist after 49 your root node)

(3) and so on, in the root node of the tree to find did node, found to continue to find your node, found to continue to look for Mother node, found on the creation of Mother node ...

Specific implementation:

Count = Len (word_list)
i = 0
While I < count: # because you need to use the index traversal list, you can only use while to traverse the list
finish = I
Start = I-num + 1 # num denotes the limit of the number of words in a phrase, and start indicates the index of the first word with that word as the end of the phrase
If start < 0:
Start = 0 # Special case where there are no words in front of the index at the beginning of processing
index = i
While index >= start: # do num times to establish nodes
If Word_list[i] in Get_dict_value (Word_freq, Word_list[index:finish]). Keys ():
Get_dict_value (Word_freq, Word_list[index:finish]) [word_list[i]][' value '] + = 1
Else
Get_dict_value (Word_freq, Word_list[index:finish]). Update ({Word_list[i]: {' value ': 1}})
Index-= 1
i + = 1
Get_dict_value function
defGet_dict_value (word_freq={}, keys=[]):    """If Keys is a string, returns the value of keys in the Word_freq dictionary. If keys is a list, use the eval () function for string concatenation and depth to find the value of keys in the Word_freq dictionary. """    ifType (keys).__name__=='Str':        returnWord_freq[keys]Else: Count=len (keys)ifCount = =0:returnWord_freqelifCount = = 1:            returnWord_freq[keys[0]]elifCount = = 2:            returnWord_freq[keys[0]][keys[1]]        elifCount = = 3:            returnWord_freq[keys[0]][keys[1]][keys[2]] #对寻找三个单词以下的词组进行特化Else: String="word_freq['"string+="'] ['". Join (keys) string+="']"            returnEval (String) #动态寻找字典的值的一般版本


    2.2.3, dictionary formatting

The data has been stored in the forest, and the next step is to format the forest as a normal dictionary.

I chose the breadth-first traversal that was easier to understand and implement than the depth-first traversal.

The principle of breadth-first traversal I don't repeat it.

defFormat_dict (word_freq={}):    """A complex dictionary of statistical phrases is formatted, formatted in the form of <str,int>"""Formated_word_freq={} phrases= []     forWordinchWord_freq.keys (): #将所有根节点放入队列中 phrases.append (word) whileLen (phrases) >0: #只要队列还有元素, it shows that there is no traversal end phrase=Phrases[0]ifLen (Get_dict_value (word_freq, phrase)) = = 1 andType (phrase).__name__=='List': formated_word_freq[' '. Join (phrase)] = Get_dict_value (word_freq, phrase) ['Value'] #搜索到叶子节点了, this node is stored in a well-formed dictionaryElse:             forNext_wordinchGet_dict_value (word_freq, phrase): Keys outside #除 "value" key-value pairs are queued to temp= []                ifType (phrase).__name__=='Str': temp.append (phrase)Else: temp.extend (phrase)ifNext_word! ='Value': Temp.append (next_word) phrases.append (temp) phrases.pop (0) #搜索完队列的第一个节点 The child node that this node is out of the team#print (formated_word_freq)    returnFormated_word_freq

3. Output dictionary (no changes)

def Output_result (word_freq):     if word_freq:         = Sorted (Word_freq.items (), key=Lambda v:v[1], reverse=True)        for in Sorted_word_freq[:10]:            print(item)

4. Main function

if __name__=="__main__":    ImportArgparse Parser=Argparse. Argumentparser () parser.add_argument ('Path') #路径 parser.add_argument ('Num') #词组单词个数 args=Parser.parse_args () path=Args.path Num=Int (args.num) buffer=process_file (path)ifBuffer:word_freq=process_buffer (buffer, num)ifNum! = 1: Word_freq=format_dict (word_freq) output_result (word_freq)

The command line accepts two parameters, one is the path to the English document, and one is the maximum number of words that make up a phrase (1 o'clock is the word count). Without this restriction, there will be a tree from the first word to the last word in the forest.

Second, Code style description

  Basic compliance with PEP8,PEP8 covers things like whitespace, line breaks between functions/classes/methods, import warnings about deprecated features, and so on, is a good rule.

defGet_dict_value (word_freq={}, keys=[]):    """If Keys is a string, returns the value of keys in the Word_freq dictionary. If keys is a list, use the eval () function for string concatenation and depth to find the value of keys in the Word_freq dictionary. """    ifType (keys).__name__=='Str':        returnWord_freq[keys]Else: Count=len (keys)ifCount = =0:returnWord_freqelifCount = = 1:            returnWord_freq[keys[0]]elifCount = = 2:            returnWord_freq[keys[0]][keys[1]]        elifCount = = 3:            returnWORD_FREQ[KEYS[0]][KEYS[1]][KEYS[2]]#to make a special search for phrases below three words        Else: String="word_freq['"string+="'] ['". Join (keys) string+="']"            returnEval (String)#a generic version of the value of a dynamically searched dictionary

Note that the basic is only in the key place, do not need to be exhaustive.

Third, the program Run command, running results

To run the command:

Python statistic.py gone_with_the_wind.txt 1
Python statistic.py gone_with_the_wind.txt 2

Four, simple performance analysis

  To run the command:

Python-m cprofile-o result.out-s Cumulative statistic.py gone_with_the_wind.txt 2

Python gprof2dot.py-f pstats result.out | Dot-tpng-o Result.png

Word Statistic Performance Analysis:

Phrase Statistical performance analysis:

In the case of Word statistics, 50% of the time spent on filtering special characters, 30% spent on the creation of dictionaries.

In the phrase statistics, the filter special characters only accounted for 10%, two layers of time in the creation of forest, 60% time in the format of the forest. In particular, the pop () function of List takes up most of the time and nearly half of the time is used for the team.

  

Program Optimization: Try to modify the breadth-first traversal without pop (). Try another data structure, where forests account for more memory than graphs.

Modified in ...

Frequency statistics of words and phrases in English documents

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.