Best Python code snippet using Kiwi_python
Count.py
Source:Count.py  
1#Author: Leo Dueker - 87354263723#Overview of Program:4# Count.py is intended to take in a single text file or multiple text files from a user and output each alpha characters frequency in5# a CSV format.  The Program also supports multiple flag options which modifies the output to the user's liking (such as distinguishing6# capital letters).The program is intended to work using command prompt for the user to provide the text files and selected flag option.789import sys10from collections import Counter11import string121314def add_frequencies(txt_file, dictionary = {}, remove_case = True):15    '''16    Add_Frequencies takes three parameters: txt_file, a dictionary, and remove_case as a boolean.  The function counts the17    characters in the given text file(s) and outputs a dictionary with the characters as keys and frequencies as values.18    Also included is a clean_string function which removes all of then non-alpha letters from the string so we only get a dictionary19    with alpha characters and thier frequencies20    '''2122    # Setting variables23    old_dict = dictionary24    new_dict = {}25    open_file = open(txt_file, 'r').read()2627    #Removing non alpha letters from string28    clean_string = ''.join([i for i in open_file if i.isalpha()])2930    # Handling case logic31    clean_string = clean_string.lower() if remove_case else clean_string3233    # Grabbing unique list of strings to be used as dictionary keys34    dict_keys = list(set(clean_string))3536    # Cycling through all the keys in the dictionary and grabbing their frequency in the text file37    for i in dict_keys:3839        sub_count = clean_string.count(i)40        new_dict[i] = sub_count4142    final_dict = dict(Counter(new_dict) + Counter(old_dict))4344    return(final_dict)45464748def main(a_list):49    '''50    a_list: list of command line arguments51    '''52    arg_list = a_list5354    # Grabbing all txt files from argv55    file_list = []5657    for x in arg_list:58        if x.find('.txt') != -1:59            file_list.append(x)60        else:61            continue6263    # Checking to see if there are more than one optional argument and throwing error if this is the case64    if ('-c' in arg_list) + ('-l' in arg_list) + ('-z' in arg_list) >1:65        raise ValueError('Provided too many optional arguments')6667    # Handling Optional Flag case -c. Which uses the case sensitive add_frequencies method68    if '-c' in arg_list:6970        #Creat initial dictionary71        dictionary_loop = {}7273        #Cycling through the files74        for file in file_list:7576            #Using Counter Method to merge two dictionaries which adds the values of common keys.77            dictionary_loop = add_frequencies(file, dictionary = dictionary_loop, remove_case = False)7879        return(dictionary_loop)8081    elif '-z' in arg_list:828384        # Dictionary Holding alphas with 0 values85        alpha_dict = dict.fromkeys(list(string.ascii_lowercase), 0)8687        #Initalizing dictionary for file88        dictionary_loop = {}8990        #Cycling through the files91        for file in file_list:9293            dictionary_loop = add_frequencies(file, dictionary = dictionary_loop, remove_case = True) #Using Counter Method to merge two dictionaries which adds the values of common keys.9495        # Updating alphabet dictionary with our updated frequencies96        alpha_dict.update(dictionary_loop)9798        # Printing in CSV99        return(alpha_dict)100101102    elif '-l' in arg_list:103104        # Grabbing argument occuring after -l argument105        text_pos  = arg_list.index('-l') + 1106        text_filter = list(arg_list[text_pos].lower())107108        #Initalizing dictionary for file109        dictionary_loop = {}110111        #Cycling through the files112        for file in file_list:113114            dictionary_loop = add_frequencies(file, dictionary = dictionary_loop, remove_case = True) #Using Counter Method to merge two dictionaries which adds the values of common keys.115116        # Filtering final dictionary to only include our letters117        filtered_dict = { key: dictionary_loop[key] for key in text_filter}118119        # Printing in CSV120        return(filtered_dict)121122    else:123124        #Initalizing dictionary for file125        dictionary_loop = {}126127        #Cycling through the files128        for file in file_list:129130            dictionary_loop = add_frequencies(file, dictionary = dictionary_loop, remove_case = True) #Using Counter Method to merge two dictionaries which adds the values of common keys.131132        # Printing in CSV133        return(dictionary_loop)134135136137138if __name__ == '__main__':139    arg_list = sys.argv140    main(arg_list)141142143144
...dc.py
Source:dc.py  
1import sys2import os3# deleting lines which were commented out during the extraction process4remove_cases = {5    "functions": [False, '// return new EvalError', '//return new EvalError'],6    "controls": [False, '// return', '//return'],7    "operations": [True, '// return'],8}9base_folder = sys.argv[1]10remove_case = sys.argv[2]11def remove_comments(filename, sw_excludes, follow_lines):12    print("Removing comments from " + filename)13    try:14        with open(filename, 'r') as fr:15            # read all lines16            lines = fr.readlines()17            # delete commented lines18            with open(filename, 'w') as fw:19                flag = False20                for line in lines:21                    # check if line starts with '// return new EvalError'22                    # if line.strip().startswith('// return new EvalError') or line.strip().startswith('//return new EvalError'):23                    if line.strip().startswith(tuple(sw_excludes)):24                        print("DELETED: " + line)25                        flag = True26                    elif flag and follow_lines and line.strip().startswith("//"):27                        print("DELETED FOLLOING: " + line)28                    else:29                        fw.write(line)30                        flag = False31    except IOError:32        print('File not found')33        sys.exit(1)34    print("-----------------------Done-----------------------")35     36# check if base_folder is a directory37if base_folder.endswith('/') or base_folder.endswith('\\'):38    # recursively search for .java files in base_folder39    for root, dirs, files in os.walk(base_folder):40        for file in files:41            if file.endswith('.java'):42                if remove_case in remove_cases.keys():43                    remove_comments(os.path.join(root, file), remove_cases[remove_case][1:], remove_cases[remove_case][0])44                else:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
