This week I had a good time with python. Yes, I have learnt few things which I feel worth to share here.
Counter:
It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. One can find out the number of occurrence of the list items.
Example:#
>>>from collections import Counter
# list1 is a list/array which contains numbers
>>>list1 = [1,2,4,5,7,3,5,0,8,5,4,5,4,5,6,7,3,1,2,0,8,3,4,5,2,1,2,3,1,2]
# Counter will convert list1 into dictionary
>>>count = Counter(list1)
>>># most_common function will give the series of all the elements and its corresponding occurrences.
>>>count.most_common()
[(5, 6), (2, 5), (1, 4), (3, 4), (4, 4), (0, 2), (7, 2), (8, 2), (6, 1)]
>>># get the most common element by sending 1 to the function
>>>count.most_common(1)
[(5, 6)]
>>>count.most_common(1)[0] # get element & no. of occurrence as dict
(5, 6)
>>>most_common = count.most_common(1)[0][0] # Get the most common element
5
Strip() :
In the past I have used strip to strip out some letters from a string. Example
>>>“AuraAuro“.strip(“A“)
“uraAuro“
But I strip() is also used to remove all whitespace at the start and end, including spaces, tabs, newlines and carriage returns.
Rename:
I was looking for a module in python which used to rename all the specific type (eg. .docs, .txt, .py) files in a particular directory.
# Go to a directory get all the files of specific type ( lets say “.xls”)
# and rename it with ‘os.rename’
>>> import glob # used to get all the dir / file from a specified path
>>>import os
>>>path = “C:\\Users\\Vaidegi\\Desktop\\*.xls“
>>>file_names_with_path = glob.glob(path+“*.xlsx“) # to get all the excel files name
>>>for i in range(len(file_names_with_path )):
. . . os.rename(file_names_with_path[i], ‘student‘+i+‘.xls‘)