Python-file character distribution [get () function and .sort (key = lambda x: x [0], reverse = False)]

File character distribution

description

Count the character distribution of the lowercase letters az in the attachment file, that is, the number of az characters, and output the result.

Please also output the total number of characters in the file.

Pay attention to the output format, each element is separated by a comma (,).

The answer may include the distribution of 26 characters in az. If a character does not appear, it is not displayed, and the output order is az order.

Input and output examples

Format example only, not final answer.

  Input Output
Example 1  
共999字符,a:11,b:22,c:33,d:44,e:55

 ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬

 

fo = open ("latex.log", "r") #open file 
t = 0 
lt = {} #create dictionary 
for item in fo: #traversal fo 
    for j in item: #statistic character number 
        t + = 1 
        if j> = 'a'and j <=' z ': 
            lt [j] = lt.get (j, 0) + 1 # Index the dictionary with the current character j, if it is, the number of times +1; if not, add it to the dictionary, Assign the current value to 0, +1 
items = list (lt.items ()) # The dictionary is converted to a list 
print ("Total {} characters" .format (t), end = '') 
#Do not wrap items.sort ( key = lambda x: x [0], reverse = False) #According to the first dimension [0], sort by default from small to large, reverse = false does not reverse 
for item in items: 
    print (", {}: {} ". format (item [0], item [1]), end = '')

 Knowledge points involved

1. .get (<element>, 0)      Take lt.get (j, 0) +1 as an example

 The value corresponding to the j element in the lt index of the dictionary.

    1) If the dictionary lt is empty, the function of this function is to detect and generate new elements, and initialize the new elements to 0 at the same time, because the new elements are encountered, the return value is +1

     2) If the dictionary lt is not empty, follow the 1) when a new element is detected, when the same element is encountered again, the return value is +1

2,.sort(key=lambda x:x[0],reverse = False)

     1) Sort () sorts by default from small to large

     2)key=lambda x:x[0]

        The letters x: x [] can be modified at will, and the sorting method is sorted according to the dimension in brackets []

        [0] Press the first dimension, [2] Press the third dimension

      3) reverse () function

        List type operation function, the result is to directly change the list itself (saving space), directly change the original list to the inverted list, the return value is empty (None), so directly quote the reverse order

        reverse = false sort by default, no reverse; reverse = true reverse

Guess you like

Origin www.cnblogs.com/Anjoras-bk/p/12697980.html