├── .gitignore ├── Basic-Scripts ├── Compress_the_string.py ├── Dat_to_CSV │ ├── README.md │ ├── dat_to_csv.py │ └── requirements.txt ├── Factorial.py ├── Geocoding and Reverse Geocoding │ ├── README.md │ ├── Sample.PNG │ ├── geocoding_and_reverse_geocoding.py │ └── requirements.txt ├── GraphColoringBacktrack.py ├── Infix_to_Postfix_Conversion │ ├── Infix_to_Postfix_Conversion.py │ └── README.md ├── List.py ├── List_4.py ├── List_Compressions.py ├── Menu_Driven.py ├── Password │ ├── README.md │ └── password.py ├── Prime.py ├── Python_Fib_Generators.py ├── README.md ├── Rock_paper_scissor.py ├── Simple_calculator.py ├── SnakeGame.py ├── String_Manipulate.py ├── TodaysDate.py ├── Zip_file_extractor │ ├── README.md │ ├── sample.PNG │ └── zip_file_extractor.py ├── advanceCalculator.py ├── anagram.py ├── area_circle.py ├── armstrong ├── ascii.py ├── automate_file_classification.py ├── average grade.py ├── balanced_paranthesis.py ├── blackjack_game.py ├── christmas_pattern.py ├── count_positive_and_negative.py ├── dictionary.py ├── ditionary.py ├── do-while.py ├── excel.py ├── fib_naci.py ├── file1.txt ├── file_example.txt ├── file_handling.py ├── file_manipulation.py ├── flames.py ├── flat_list.py ├── forWithList.py ├── for_loop.py ├── for_loop2.py ├── for_loop3.py ├── function_1.py ├── function_2.py ├── function_parameter.py ├── function_parameter_2.py ├── get_ip_address.py ├── github_opener.py ├── guessgameadv.py ├── guessinggame.py ├── gui-tk.py ├── hangman.py ├── happy_numbers.py ├── hello.py ├── if_elif.py ├── if_else.py ├── if_else_2.py ├── img_to_ascii.py ├── insert_sort.py ├── int_to_en.py ├── leap_year.py ├── letter_counter.py ├── list_1.py ├── list_2.py ├── list_tuple_dict.py ├── location_ip ├── magic8Ball.py ├── magic_square.py ├── math_expression.py ├── math_func.py ├── maxBetween2NumbersWithoutIF.py ├── merge_sort.py ├── myPets.py ├── odd_even.py ├── palindrome.py ├── password_checker.py ├── picnicTable.py ├── prime_numbers.py ├── pyperClip.py ├── quad_equation.py ├── rand_range.py ├── random.py ├── random_password.py ├── recursion.py ├── reverse.py ├── scrap_quotes.py ├── secure your password.py ├── selection_sort.py ├── send_mail.py ├── simple-address-book.py ├── simple_file_write.py ├── simple_interest.py ├── snake_to_camel.py ├── staicase_pattern.py ├── starpattern.py ├── string_practice.py ├── sum_lst_index.py ├── sum_of_items_list.py ├── table.py ├── tic-tac-toe-1.py ├── tic-tac-toe.py ├── time.py ├── towerofhanoi.py ├── translate.py ├── tuple_1.py ├── tuple_2.py ├── validateInput.py ├── watermark_pdf.py ├── while1.py ├── while_loop2.py ├── word_encrypt.py ├── yourname.py └── zeroDivide.py ├── CODE_OF_CONDUCT.md ├── Calculator_GUI ├── Readme.md ├── calculator.py └── calculator_.png ├── Chat example with socket lib ├── client.py └── server.py ├── Contribution.md ├── Image-Processing ├── Basic_OpenCV │ ├── README.md │ └── rose.jpg ├── Canny Edge Detection │ ├── CannyEdgeDetection.py │ ├── Canny_EdgeDetection_using_math.py │ ├── Images │ │ ├── glimpse all result.JPG │ │ ├── input image.JPG │ │ ├── pic1.JPG │ │ ├── pic2.JPG │ │ ├── res1pic1.JPG │ │ ├── res2pic2.JPG │ │ ├── res3sudoku.JPG │ │ └── tograyscale.JPG │ └── Readme.md ├── Car_detection │ └── README.md ├── Cartoonify Image │ ├── Cartoonify.py │ ├── README.md │ └── images │ │ ├── Cartoonified Image.PNG │ │ ├── Original Image.PNG │ │ └── sunset.jpg ├── Color_Detection │ ├── Readme.md │ ├── color_detection.py │ ├── color_sample.png │ └── colors.csv ├── Detecting Contours │ ├── Readme.md │ ├── detecting_geometrical_shapes.py │ ├── output2.JPG │ └── shapes.png ├── Face_detection │ ├── Face_detection.py │ └── README.md ├── HANDWRITING RECOGNIZER │ ├── hand.py │ └── readme.md ├── Hough_Transform │ ├── HoughTransform_without_opencv.py │ ├── hough_Transform.py │ ├── image.jfif │ └── readme.md ├── Image To Sepia Effect │ ├── README.md │ ├── Taj_Mahal.jpg │ ├── original.jpg │ ├── sepia image convertor.py │ └── sepia.jpg ├── ImageCropper │ ├── Data │ │ ├── CropDEMO.gif │ │ ├── Man_United.jpeg │ │ └── cropped image1.png │ ├── README.md │ └── crop.py ├── Image_Crop_(resize) │ ├── Image_crop.py │ ├── README.md │ └── rose.jpg ├── Image_filters_using_convolution │ ├── 3D_convolve.py │ ├── README.md │ └── images │ │ ├── after.png │ │ └── before.png ├── Invisible_cloak │ ├── README.md │ └── cloak.py ├── JpgToPngConvertor │ ├── JpgToPngConvertor.py │ ├── README.md │ └── Source_Images │ │ ├── bulbasaur.jpg │ │ ├── charmander.jpg │ │ ├── pikachu.jpg │ │ └── squirtle.jpg ├── Qr_scanner │ ├── Qr_scanner.py │ ├── README.md │ └── qr.png ├── README.md └── ocr-img-to-txt │ ├── ocr-img-to-txt.md │ └── ocr-img-to-txt.py ├── LICENSE ├── README.md ├── System-Automation-Scripts ├── Amazon-price-tracker │ ├── README.md │ ├── images │ │ ├── confirm.png │ │ ├── lesssecure.png │ │ └── single.png │ ├── mail_in_python.py │ ├── price_logger.txt │ └── price_tracker.py ├── Automate-Telegram │ ├── README.md │ ├── automate_telegram.py │ ├── code.png │ ├── login.png │ ├── send.png │ └── working.PNG ├── Automatic attending meet │ ├── Class_buddy.py │ └── Readme.md ├── Email_Client │ ├── README.md │ ├── email_client.py │ ├── email_client_test.py │ ├── password.txt │ └── test.txt ├── FolderSorter.py ├── Google │ ├── Automating_Google.py │ ├── Automating_Google_Search.py │ └── README.md ├── PDF_Tables_To_CSV │ ├── .gitignore │ ├── README.md │ ├── app.py │ └── preview.gif ├── PingScanner.py ├── Questions_from_Project_Euler │ ├── README.md │ ├── euler.py │ └── images │ │ ├── euler_home.PNG │ │ ├── euler_questions.PNG │ │ └── question1.PNG ├── README.md ├── Story Reader │ ├── Readme.md │ ├── audiobook.png │ ├── main.py │ └── mybook.pdf ├── Twitter Automation │ ├── README.md │ ├── Twitter Automation.py │ └── twitter_image.PNG ├── WhatsApp-message-automation │ ├── README.md │ ├── abcd.PNG │ ├── automate-messages.py │ ├── confirm.png │ ├── frequent.PNG │ ├── qrcode.PNG │ ├── script.PNG │ └── search.PNG ├── Word detector │ ├── README.md │ └── word_detector.py ├── Zoom automation │ ├── Readme.md │ ├── img │ │ ├── join.png │ │ ├── s1.png │ │ ├── s2.png │ │ └── s3.png │ └── zoom.py ├── automail.py ├── automate-whatsapp.py ├── junk_organiser.py ├── pdfCreator.py ├── processClose.py ├── pypdf.py ├── verify_email.py ├── whatsappbot.py ├── zipFileConverter.py └── zipFileExtracterCommandLine.py ├── Web-Scraping ├── Covid-19 Statics │ ├── README.md │ └── code.py ├── Cricbuzz Scrap │ ├── Readme.md │ └── crik_buzz.py ├── E-Commerce Website │ ├── README.md │ ├── WebScraping.py │ └── products.csv ├── Hacktoberfest_Events │ ├── README.md │ ├── hacktoberfest_events.py │ └── requirements.txt ├── IMDB_TopMovies │ ├── Output │ │ └── imdb.csv │ ├── README.md │ └── imdb_topmovies.py ├── Instagram-scraper │ ├── README.md │ └── instagram-scraper.py ├── Instagram │ ├── README.md │ └── instagram_count.py ├── Medium-Articles-Details-Scrapping │ ├── .gitignore │ ├── README.md │ ├── app │ │ └── __init__.py │ ├── run.py │ └── terminal-preview.PNG ├── Medium_article_downloader │ ├── Article_downloader.py │ ├── README.md │ └── medium.PNG ├── Movie Recommendation │ ├── README.md │ └── code.py ├── Questions_from_Project_Euler │ ├── README.md │ ├── euler.py │ └── images │ │ ├── euler_home.PNG │ │ ├── euler_questions.PNG │ │ └── question1.PNG ├── README.md ├── Reddit Scrapper │ ├── .gitignore │ ├── README.md │ ├── app.py │ ├── output │ │ ├── config.PNG │ │ ├── csv.PNG │ │ └── result.csv │ └── requirements.txt ├── ScrappingHackerNewsWebsite │ ├── README.md │ └── ScrappingHackerNewsWebsite.py ├── Songs_Lyrics │ ├── README.md │ ├── lyrics_op.png │ └── song_lyrics.py ├── Times_of_india │ ├── README.md │ ├── TOI.png │ └── Times_of_india.py ├── amazon_reviews_scraping │ ├── README.md │ ├── items.py │ ├── middlewares.py │ ├── pipelines.py │ ├── settings.py │ └── spiders │ │ ├── __init__.py │ │ ├── __pycache__ │ │ └── amazon_reviews.cpython-38.pyc │ │ └── scraper.py └── links extractor │ ├── README.md │ └── links-extractor.py └── _config.yml /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /Basic-Scripts/Compress_the_string.py: -------------------------------------------------------------------------------- 1 | from itertools import groupby 2 | uncompressed = str(input("Enter string to compress: ")) # user input for string 3 | print(*[(len(list(value)), str(key)) for key, value in groupby(uncompressed)]) # logic to print occurence of values in string 4 | -------------------------------------------------------------------------------- /Basic-Scripts/Dat_to_CSV/README.md: -------------------------------------------------------------------------------- 1 | ## Dat to CSV 2 | 3 | This simple script can be used to convert files in ".dat" format to ".csv" format. 4 | 5 | 6 | ## How to use this script? 7 | 8 | 1.Install the required libraries by: 9 | 10 | pip install -r requirements.txt 11 | 12 | 2. Open your command prompt in the directory of the script and type the following: 13 | 14 | python dat_to_csv.py -l 15 | 16 | Example: 17 | 18 | python dat_to_csv.py -l awesome.dat 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Basic-Scripts/Dat_to_CSV/dat_to_csv.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import argparse 3 | 4 | # Code to add the command line interface 5 | parser = argparse.ArgumentParser() 6 | parser.add_argument("-l", "--datafile", required=True, help="data file ") 7 | args = vars(parser.parse_args()) 8 | 9 | #Catching the user defined data file 10 | data_file = args['datafile'] 11 | 12 | #Logic to make sure it is a data file.A data file ends with .dat extension 13 | 14 | if data_file.endswith(".dat"): 15 | 16 | #Storing the name of the file 17 | file_name = data_file.split(".")[0] 18 | 19 | #Collecting data of the file in a pandas object 20 | data_of_the_file = pd.read_csv(data_file, sep="\s+") 21 | 22 | #Converting the pandas object into a csv 23 | data_of_the_file.to_csv(file_name+".csv", index=False) 24 | print("Your csv file has been created successfully!!!") 25 | else: 26 | print("Invalid data file") 27 | 28 | #Sample Input-Output: 29 | 30 | #Input(At the command line): python dat_to_csv -l awesome.dat 31 | #Output: awesome.csv 32 | -------------------------------------------------------------------------------- /Basic-Scripts/Dat_to_CSV/requirements.txt: -------------------------------------------------------------------------------- 1 | numpy==1.19.1 2 | pandas==1.1.1 3 | python-dateutil==2.8.1 4 | pytz==2020.1 5 | six==1.15.0 6 | -------------------------------------------------------------------------------- /Basic-Scripts/Factorial.py: -------------------------------------------------------------------------------- 1 | # Python program to find the factorial of a number provided by the user. 2 | 3 | # change the value for a different result 4 | num = 7 5 | 6 | # uncomment to take input from the user 7 | #num = int(input("Enter a number: ")) 8 | 9 | factorial = 1 10 | 11 | # check if the number is negative, positive or zero 12 | if num < 0: 13 | print("Sorry, factorial does not exist for negative numbers") 14 | elif num == 0: 15 | print("The factorial of 0 is 1") 16 | else: 17 | for i in range(1,num + 1): 18 | factorial = factorial*i 19 | print("The factorial of",num,"is",factorial) 20 | -------------------------------------------------------------------------------- /Basic-Scripts/Geocoding and Reverse Geocoding/README.md: -------------------------------------------------------------------------------- 1 | ### Geocoding and Reverse Geocoding 2 | 3 | #### This script takes an address and return its latitude and longitude.This process is called geocoding 4 | #### It can also perform the opposite operation that is take latitude, longitude and provide address. 5 | 6 | #### I have used the LocationIQ website's geocoding api inorder to solve this problem. 7 | 8 | #### In order to run this script you need to have a private token which is just a key for the api.. 9 | 10 | #### To obtain your own private token create a *free account* at https://locationiq.com/ and replace my private token with yours. 11 | 12 | #### Remember, *don't share* your private token with anyone if you use your personal email for account creation. 13 | 14 | #### Install the dependencies by using: 15 | 16 | pip install -r requirements.txt 17 | 18 | #### An Example of the script in action: 19 | 20 | Sample 21 | 22 | 23 | -------------------------------------------------------------------------------- /Basic-Scripts/Geocoding and Reverse Geocoding/Sample.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Basic-Scripts/Geocoding and Reverse Geocoding/Sample.PNG -------------------------------------------------------------------------------- /Basic-Scripts/Geocoding and Reverse Geocoding/requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2020.6.20 2 | chardet==3.0.4 3 | idna==2.10 4 | requests==2.24.0 5 | urllib3==1.25.10 6 | -------------------------------------------------------------------------------- /Basic-Scripts/Infix_to_Postfix_Conversion/Infix_to_Postfix_Conversion.py: -------------------------------------------------------------------------------- 1 | # function to convert infix to postfix using array as stack 2 | def infix_to_postfix(infix_expression): 3 | """ 4 | Function to change infix expression to postfix one 5 | Params: 6 | infix_expression: Infix Expression provided by user 7 | Returns: 8 | postfix_expression: Postfix Expression convertef from Infix one 9 | """ 10 | 11 | # initially empty stack 12 | stack = [] 13 | # initially empty postfix_expression 14 | postfix_expression = "" 15 | for char in infix_expression: 16 | # if an operand then put it directly in postfix expression 17 | if char not in operators: 18 | postfix_expression += char 19 | # else if operators should be put in stack 20 | elif char == "(": 21 | """append function to push 22 | elements in the stack""" 23 | stack.append("(") 24 | elif char == ")": 25 | while stack and stack[-1] != "(": 26 | postfix_expression += stack.pop() 27 | """ pop function to pop 28 | elements from stack in LIFO order """ 29 | stack.pop() 30 | else: 31 | """if priority of char in infix_expression is less than or equal to 32 | char at stack[-1] pop out and put in postfix_expression""" 33 | while ( 34 | stack and stack[-1] != "(" and priorities[char] <= priorities[stack[-1]] 35 | ): 36 | postfix_expression += stack.pop() 37 | stack.append(char) 38 | while stack: 39 | postfix_expression += stack.pop() 40 | return postfix_expression 41 | 42 | 43 | # Set of operators 44 | operators = set(["+", "-", "*", "/", "(", ")", "^"]) 45 | 46 | # dictionary having priorities 47 | priorities = {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3} 48 | 49 | print("Input") 50 | infix_expression = input("Enter infix expression\n") 51 | print("Output") 52 | 53 | # Displaying the Output 54 | print("Postfix expression: ", infix_to_postfix(infix_expression)) 55 | -------------------------------------------------------------------------------- /Basic-Scripts/Infix_to_Postfix_Conversion/README.md: -------------------------------------------------------------------------------- 1 | ### Infix to Postfix 2 | 3 | > • In Infix expression operator is in between every pair of operands.
4 | > • In Postfix expression, the operator is followed for every pair of operands. 5 | 6 | > Infix expression is converted to postfix conversion using Stack. 7 | > Postfix expression is evaluated using Stack in Left to Right order. 8 | 9 | ##### If the scanned character is operand, show it as output. Else, If precedence of scanned operator is greater than the precedence of the operator in the stack,push it. 10 | 11 | > Else, Pop all the operators from the stack which are greater than or equal to in precedence than that of the scanned operator. 12 | 13 | • If the scanned input is '(', push it into stack
14 | • If the scanned input is ')' ,pop the stack and the output it until '(' comes.
15 | • Repeat above steps. Continue Pop and output from stack until it becomes empty. 16 | 17 | ##### It makes the code more efficient and even reduces the time complexity. 18 | ### Constraints 19 | """ 20 | Input: 21 | Enter infix expression: A+C*(B^D-E)^(G+H*K)-K 22 | Output: 23 | Postfix expression: ACBD^E-GHK*+^*+K- 24 | 25 | Time Complexity : O(n) 26 | Space Complexity: Θ(n) 27 | """ 28 | -------------------------------------------------------------------------------- /Basic-Scripts/List.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | spam = ['ankit','arjun','arun'] 3 | print(spam) 4 | spam.append('anurag') 5 | print(spam) 6 | spam.insert(1,'elliot') 7 | print(spam) 8 | spam.remove('arun') 9 | print(spam) 10 | -------------------------------------------------------------------------------- /Basic-Scripts/List_4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | spam = [2,5,3.14,1.1,7] 3 | spam.sort() 4 | print(spam) 5 | -------------------------------------------------------------------------------- /Basic-Scripts/List_Compressions.py: -------------------------------------------------------------------------------- 1 | n = int(input("Enter a number: ")) 2 | print("A list of numbers of squares up to the given number is:") 3 | print([x**2 for x in range(n)]) 4 | print("Converting the list of numbers till the given number to string data type:") 5 | print([str(x) for x in range(n)]) -------------------------------------------------------------------------------- /Basic-Scripts/Password/README.md: -------------------------------------------------------------------------------- 1 |

Hard to guess easy to remember

2 |

Python script to generate a password which is almost impossible to guess by a attacker, by using the easily remembered words of a user day to day life.

3 | 4 | Here I use built-in python module name random use to make random choice. 5 | -------------------------------------------------------------------------------- /Basic-Scripts/Prime.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #Program to find prime and non prime number 3 | no=int(input("Enter the number:\n")) 4 | b=0 5 | for i in {1,50}: 6 | 7 | if no%i == 0: 8 | b=b+1 9 | 10 | if b == 2: 11 | print(no,"is prime number:\n") 12 | else: 13 | print(no,"is non prime number:\n") 14 | -------------------------------------------------------------------------------- /Basic-Scripts/Python_Fib_Generators.py: -------------------------------------------------------------------------------- 1 | def python_gen(limit): 2 | a, b = 0, 1 3 | while a < limit: 4 | yield a 5 | a, b = b, a + b 6 | 7 | 8 | num = int(input("Up to whichnumber do you want to the fib number: ")) 9 | for i in python_gen(num): 10 | print(i) -------------------------------------------------------------------------------- /Basic-Scripts/README.md: -------------------------------------------------------------------------------- 1 | #Basic-Scripts 2 | Basic-Scripts is a collection of basic python scripts for newbies in python to understand basic concept of python programming. 3 | -Data Structure in python 4 | -Conditional 5 | -Loop 6 | -Exception handling 7 | -Algorithms 8 | -OOP 9 | -Class 10 | -Object 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Basic-Scripts/String_Manipulate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | print('How are you?') 3 | feeling = input() 4 | if feeling.lower()=='great': 5 | print('I feel great too!') 6 | else: 7 | print('I hope the rest of day is good!') 8 | -------------------------------------------------------------------------------- /Basic-Scripts/TodaysDate.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | now = datetime.now() 4 | 5 | mm = str(now.month) 6 | 7 | dd = str(now.day) 8 | 9 | yyyy = str(now.year) 10 | 11 | hour = str(now.hour) 12 | 13 | mi = str(now.minute) 14 | 15 | ss = str(now.second) 16 | 17 | print (mm + "/" + dd + "/" + yyyy + " " + hour + ":" + mi + ":" + ss) 18 | -------------------------------------------------------------------------------- /Basic-Scripts/Zip_file_extractor/README.md: -------------------------------------------------------------------------------- 1 | ## Extract zip files 2 | 3 | This script takes a zip file as input and extracts its content into a separate folder. 4 | The folder is named same as the input zip file and is saved in the current directory 5 | 6 | ### How to use this? 7 | Just type the following in the command prompt: 8 | 9 | python zip_file_extractor.py -l 10 | 11 | Example: 12 | 13 | python zip_file_extractor.py -l Awesome.zip 14 | 15 |

16 | sample 17 |

18 | -------------------------------------------------------------------------------- /Basic-Scripts/Zip_file_extractor/sample.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Basic-Scripts/Zip_file_extractor/sample.PNG -------------------------------------------------------------------------------- /Basic-Scripts/Zip_file_extractor/zip_file_extractor.py: -------------------------------------------------------------------------------- 1 | import os 2 | import zipfile 3 | import sys 4 | import argparse 5 | 6 | # Code to add the cli 7 | parser = argparse.ArgumentParser() 8 | parser.add_argument("-l", "--zippedfile", required=True, help="Zipped file") 9 | args = vars(parser.parse_args()) 10 | 11 | #Catching the user defined zip file 12 | zip_file = args['zippedfile'] 13 | 14 | file_name = zip_file 15 | 16 | #To check if the entered zip file is present in the directory 17 | if os.path.exists(zip_file) == False: 18 | sys.exit("No such file present in the directory") 19 | 20 | #Function to extract the zip file 21 | def extract(zip_file): 22 | file_name = zip_file.split(".zip")[0] 23 | if zip_file.endswith(".zip"): 24 | 25 | #Will use this to save the unzipped file in the current directory 26 | current_working_directory = os.getcwd() 27 | new_directory = current_working_directory + "/" + file_name 28 | #Logic to unzip the file 29 | with zipfile.ZipFile(zip_file, 'r') as zip_object: 30 | zip_object.extractall(new_directory) 31 | print("Extracted successfully!!!") 32 | else: 33 | print("Not a zip file") 34 | 35 | extract(zip_file) 36 | -------------------------------------------------------------------------------- /Basic-Scripts/advanceCalculator.py: -------------------------------------------------------------------------------- 1 | # Script of Advance Calculator using Python using regexp module 2 | 3 | # importing the regexp module 4 | import re 5 | 6 | # salutation and providing termination condition. 7 | print("Welcome! I am your Advance Calculator.") 8 | print("Type 'quit' to terminate.\n") 9 | 10 | #declaring global variables 11 | previous_value = 0 12 | flag = True 13 | 14 | # Defining non parametrized function to perform all the operations. 15 | def calculate(): 16 | global flag 17 | global previous_value 18 | 19 | equation = "" 20 | 21 | # Taking input from the user. 22 | if previous_value == 0: 23 | equation = input("Give me something to calculate:") 24 | else: 25 | equation = input(str(previous_value)) 26 | 27 | # Termination step. 28 | if equation == 'quit': 29 | print("You exit.") 30 | print("See you next time.") 31 | flag = False 32 | else: 33 | equation = re.sub('[a-zA-z,.:()" "]', '', equation) 34 | # For security point of view here we eliminate all the letters and keep only numerical characters, if entered by the user. 35 | 36 | # Calculating the results. 37 | if previous_value == 0: 38 | previous_value = eval(equation) 39 | else: 40 | previous_value = eval(str(previous_value) + equation) 41 | 42 | # Calling the function within the infinite loop. 43 | # On execution will continue to calculate until the user enters 'quit' . 44 | while flag: 45 | calculate() 46 | 47 | #end of the script -------------------------------------------------------------------------------- /Basic-Scripts/anagram.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Sat Aug 13 19:25:33 2020 4 | 5 | @author: Gulshan 6 | """ 7 | 8 | 9 | 10 | from collections import Counter 11 | 12 | def check_anagram(string1, string2): 13 | return Counter(string1) == Counter(string2) 14 | 15 | 16 | if __name__ == '__main__': 17 | string1 = input("Enter First String: ") 18 | string2 = input("Enter Second String: ") 19 | if check_anagram(string1, string2): 20 | print("Strings are Anagram!") 21 | else: 22 | print("Strings are not Anagram!") 23 | 24 | -------------------------------------------------------------------------------- /Basic-Scripts/area_circle.py: -------------------------------------------------------------------------------- 1 | # Python program to find Area of a circle 2 | 3 | def findArea(r): 4 | PI = 3.142 5 | return PI * (r*r); 6 | 7 | # Driver method 8 | number = int(input("Enter the radius ")) 9 | print("Area is %.6f" % findArea(number)); 10 | 11 | # This code is contributed by Chinmoy Lenka 12 | -------------------------------------------------------------------------------- /Basic-Scripts/armstrong: -------------------------------------------------------------------------------- 1 | import math 2 | num = int(input("Enter a number to check whether it is Armstrong or not : ")) 3 | 4 | sumEl = 0 5 | temp = num 6 | while temp > 0: 7 | # To pick out each digits from the number starting from One's place and gradually towards hundred's place 8 | digit = temp % 10 9 | # Continue adding the cube of each digit obtained from previous step 10 | sumEl += digit ** 3 11 | # Floor function is used to determine the closest integer value 12 | temp = math.floor(temp / 10) 13 | 14 | if num == sumEl: 15 | print("Its an armstrong number") 16 | else: 17 | print("Its not an armstrong number") 18 | -------------------------------------------------------------------------------- /Basic-Scripts/ascii.py: -------------------------------------------------------------------------------- 1 | # Python code to get the ASCII value of the character 2 | 3 | #taking input from the user 4 | char_input = input("Enter a character to print it's ASCII value\t") 5 | 6 | # printing the ASCII value, using the ord() function in python 7 | print("The ASCII value of ",char_input,"is ",ord(char_input)) -------------------------------------------------------------------------------- /Basic-Scripts/automate_file_classification.py: -------------------------------------------------------------------------------- 1 | 2 | #the rules.txt file contains the necessary info and rules for moving the files 3 | 4 | import os 5 | import shutil 6 | 7 | #the following lines indicate the path of the rules.txt file 8 | 9 | file_path = os.getcwd() 10 | file_name = os.path.join(file_path, "rules.txt") 11 | 12 | 13 | #get the path and the mode from rules.txt 14 | 15 | file_t = open(file_name,'r') 16 | path = file_t.readline() 17 | mode = file_t.readline() 18 | mode = mode.strip("\n") 19 | path1 = path.strip("\n") 20 | 21 | #the following function returns a dictionary that contains the rules. The dictionary's keys behave as extensions of the files and values act as moved paths 22 | 23 | dict1 = {} 24 | def rules(): 25 | dict1 = {} 26 | for each in file_t: 27 | each = each.strip("\n") 28 | if each.split(":",1)[0]: 29 | file_ext,dest_path = each.split(":",1) 30 | file_ext = file_ext.strip() 31 | dest_path = dest_path.strip() 32 | dict1[file_ext] = dest_path 33 | return dict1 34 | 35 | 36 | #the following function takes a list of files and moves the files to their resp files 37 | 38 | def file_move(files_list): 39 | for file in files_list: 40 | if "." in file: 41 | ext = file.rsplit(".",1)[1] 42 | ext = ext.strip() 43 | if ext in dict1: 44 | dst = dict1[ext] 45 | try: 46 | print (file) 47 | shutil.move(file,dst) 48 | except Exception as e: 49 | print (e) 50 | 51 | #the following function is used when a simple mode is selected 52 | 53 | def single_dir(path1): 54 | os.chdir(path1) 55 | files = os.listdir(".") 56 | file_move(files) 57 | 58 | #the following function is used when recursive mode is selected 59 | 60 | def rec_dirs(path1): 61 | for root,dirs,files in os.walk(path1,topdown=True,onerror=None,followlinks=False): 62 | #print files 63 | os.chdir(root) 64 | file_move(files) 65 | print("files are moved") 66 | 67 | dict1 = rules() 68 | 69 | rec_dirs(path1) 70 | 71 | 72 | -------------------------------------------------------------------------------- /Basic-Scripts/average grade.py: -------------------------------------------------------------------------------- 1 | grades = [] 2 | n = 0 3 | v= 0 4 | average = 0 5 | 6 | while True: 7 | 8 | mark = input("Insert one Mark: ") 9 | 10 | 11 | if mark == "-1": 12 | grades.sort() 13 | grades.pop(0) 14 | for i in grades: 15 | v = v + int(i) 16 | average = v / (n-1) 17 | 18 | print("Grades list: " + str(grades)) 19 | print("Average : " + str(average)) 20 | quit() 21 | 22 | else: 23 | grades.append(mark) 24 | n = n + 1 25 | 26 | #this program make an averange until you insert "-1", eliminating the lowest one. -------------------------------------------------------------------------------- /Basic-Scripts/balanced_paranthesis.py: -------------------------------------------------------------------------------- 1 | openBracketList = ["[", "{", "("] 2 | closeBracketList = ["]", "}", ")"] 3 | 4 | 5 | def check_parentheses(data: str) -> str: 6 | """ 7 | check_parentheses() : Will take a string as an arguement and each time when an open parentheses is encountered 8 | will push it in the stack, and when closed parenthesis is encountered, 9 | will match it with the top of stack and pop it. 10 | 11 | Parameters: 12 | data (str): takes a string. 13 | 14 | Returns: 15 | str: Returns a string value whether string passed is balanced or Unbalanced. 16 | """ 17 | stack = [] 18 | for index in data: 19 | if index in openBracketList: 20 | stack.append(index) 21 | elif index in closeBracketList: 22 | position = closeBracketList.index(index) 23 | if (len(stack) > 0) and ( 24 | openBracketList[position] == stack[len(stack) - 1] 25 | ): 26 | stack.pop() 27 | else: 28 | return "Unbalanced" 29 | if len(stack) == 0: 30 | return "Balanced" 31 | else: 32 | return "Unbalanced" 33 | 34 | 35 | if __name__ == "__main__": 36 | 37 | data = input("Enter the string to check:\t") 38 | result = check_parentheses(data) 39 | print(result) 40 | 41 | -------------------------------------------------------------------------------- /Basic-Scripts/christmas_pattern.py: -------------------------------------------------------------------------------- 1 | #Python Program to print a simple christmas tree pattern using asterisk 2 | 3 | def christmastree(level): #function definition 4 | ''' 5 | Functions prints the pattern of christmas tree 6 | params: 7 | level: inputs the height of the tree 8 | returns: 9 | None 10 | 11 | ''' 12 | a=level-1 13 | b=1 14 | for image in range(0,level): 15 | for pixel in range(0,a): 16 | print(' ',end='') 17 | for image in range(0,b): 18 | print('*',end='') 19 | for pixel in range(0,a): 20 | print(' ',end='') 21 | b=b+2 22 | a=a-1 23 | print() 24 | for l in range(3): 25 | print(' '*(level-2),'*') 26 | 27 | 28 | 29 | if __name__ == "__main__": #main function 30 | 31 | level= int(input("Enter the height of christmas tree (Integer less than 30):")) #inputs the height of the tree 32 | 33 | christmastree(level) #function calling 34 | 35 | ''' 36 | Sample Output : 37 | Enter the height of christmas tree (Integer less than 30):10 38 | 39 | * 40 | *** 41 | ***** 42 | ******* 43 | ********* 44 | *********** 45 | ************* 46 | *************** 47 | ***************** 48 | ******************* 49 | * 50 | * 51 | * 52 | 53 | ''' 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /Basic-Scripts/count_positive_and_negative.py: -------------------------------------------------------------------------------- 1 | # Python program to count positive and negative numbers in a List given by user 2 | def count_pos_neg(list1): 3 | ''' we have to to count total number of positive elements and total number of negative number so we iterate the list1 and then we check every element wheather 4 | it is greater than 0 or not. if element is grater than or equal to 0 then we count it as positive element and if it is small then 0 then we count it as negative''' 5 | pos_count, neg_count = 0, 0 6 | for num in list1: # iterating each number in list 7 | if num>=0: # checking condition 8 | pos_count += 1 9 | else: 10 | neg_count += 1 11 | print("Positive numbers in the list: ", pos_count) 12 | print("Negative numbers in the list: ", neg_count) 13 | 14 | #main program 15 | if __name__ == "__main__": 16 | num = int(input("Enter number of elements: ")) 17 | #list of numbers 18 | lst = [] 19 | for index in range(0,num): 20 | #print() 21 | ele=int(input("Enter "+str(index)+"th element: ")) 22 | lst.append(ele) 23 | count_pos_neg(lst) 24 | -------------------------------------------------------------------------------- /Basic-Scripts/dictionary.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #dictionary in python 3 | 4 | #creating empty dictionary 5 | my_dict = {} 6 | 7 | print("Empty Dictionary: ") 8 | print(my_dict) 9 | 10 | #Creating a diictionary with int keys and string values then printing it 11 | 12 | my_dict = {1: 'Apple', 2: 'Orange', 3: 'Banana'} 13 | print(my_dict) 14 | 15 | #You can access the items of a dictionary by referring to its key name, inside square brackets: 16 | 17 | orange = my_dict[2] 18 | print(orange) 19 | 20 | #Creating a diictionary with string keys and printing it 21 | my_dict = { 22 | "brand": "Ford", 23 | "model": "Mustang", 24 | "year": 1964 25 | } 26 | print(my_dict) 27 | 28 | #Another example of accessing items from a dictionary by its keys 29 | 30 | model = my_dict["model"] 31 | print(my_dict) 32 | 33 | #looping through all the keys in dictionary and printing them 34 | 35 | for key in my_dict: 36 | print('key in dictionary: ',key) 37 | 38 | #looping through all the values in dictionary and printing them 39 | 40 | for value in my_dict.values(): 41 | print('value in dictionary:',value) 42 | 43 | #looping through all the key and values in dictionary and printing them 44 | for key, value in my_dict.items(): 45 | print(key, value) 46 | 47 | 48 | -------------------------------------------------------------------------------- /Basic-Scripts/ditionary.py: -------------------------------------------------------------------------------- 1 | 2 | my_dict={} 3 | my_dict['name']=input('Enter Your Name:') 4 | my_dict['mail']=input('Enter Your Mail:') 5 | 6 | print(my_dict) 7 | -------------------------------------------------------------------------------- /Basic-Scripts/do-while.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | i = 1 4 | 5 | while True: 6 | print(i) 7 | i = i + 1 8 | if(i > 3): 9 | break 10 | -------------------------------------------------------------------------------- /Basic-Scripts/excel.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this script we're going to create a simple excel file with 3(Three) columns 3 | Name | Age | Gender 4 | """ 5 | 6 | 7 | 8 | # xlwt module helps make a new excel file 9 | import xlwt 10 | 11 | # create a dictionary with information 12 | DATA_ = { 13 | 'Person1' : { 14 | 'Name' : 'Bill Gates', 15 | 'Age' : 63, 16 | 'Gender' : 'Male' 17 | }, 18 | 'Person2' : { 19 | 'Name' : 'Sheryl Sandberg', 20 | 'Age' : 50, 21 | 'Gender' : 'Female' 22 | }, 23 | 'Person3' : { 24 | 'Name' : 'Tim Cook', 25 | 'Age' : 58, 26 | 'Gender' : 'Male' 27 | }, 28 | } 29 | 30 | # first create a new workbook 31 | workbook = xlwt.Workbook() 32 | 33 | # add a new sheet to the workbook 34 | sheet = workbook.add_sheet('Sheet1') 35 | 36 | # create columns 37 | sheet.write(0,0,'Name') 38 | sheet.write(0,1,'Age') 39 | sheet.write(0,2,'Gender') 40 | 41 | 42 | # we will keep counter running until we loop through all the persons inside DATA_ 43 | counter = 1 44 | 45 | # now lets get the details from the DATA_ dict and insert them into our excel sheet 46 | for k, v in DATA_.items(): 47 | sheet.write(counter, 0, v['Name']) 48 | sheet.write(counter, 1, v['Age']) 49 | sheet.write(counter, 2, v['Gender']) 50 | 51 | # now increment the counter each time 52 | # this will make sure that information are added on new line for each person 53 | counter += 1 54 | 55 | # time to save the workbook 56 | workbook.save('details.xls') 57 | -------------------------------------------------------------------------------- /Basic-Scripts/fib_naci.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | def fib(n): # write Fibonacci series up to n 4 | a, b = 0, 1 5 | while a < n: 6 | print(a, end=' ') 7 | a, b = b, a+b 8 | print(a,b) 9 | 10 | fib(5) 11 | -------------------------------------------------------------------------------- /Basic-Scripts/file1.txt: -------------------------------------------------------------------------------- 1 | Hello World 2 | -------------------------------------------------------------------------------- /Basic-Scripts/file_example.txt: -------------------------------------------------------------------------------- 1 | Hello World! 2 | -------------------------------------------------------------------------------- /Basic-Scripts/file_handling.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #how to handle files using python 3 | 4 | #open and write to a file, then read 5 | with open('file.txt', 'w') as f: 6 | f.write('Hello World, this is a script to learn hoe to read and write files in Python') 7 | 8 | with open('file.txt', 'r') as f: 9 | content = f.readlines() 10 | for line in content: 11 | print(line) 12 | -------------------------------------------------------------------------------- /Basic-Scripts/file_manipulation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Example 4 | file = open('Scripts/file_example.txt', 'w', encoding='utf-8') 5 | 6 | print(file.write('Hello World!\n')) 7 | 8 | # Open and View file_example.txt 9 | 10 | file.close() 11 | -------------------------------------------------------------------------------- /Basic-Scripts/flat_list.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | # return flat list from input list 3 | 4 | import json 5 | 6 | user_input = input('Enter a list with json format ...\n>') 7 | 8 | try: 9 | my_list = json.loads(user_input) 10 | except json.decoder.JSONDecodeError: 11 | print('invalid json input. unable to convert inout json to list !!!') 12 | 13 | if not isinstance(my_list, list): 14 | print('only list(array) are allowed !!!') 15 | exit(1) 16 | 17 | def flat(input_list): 18 | result_list = [] 19 | for item in input_list: 20 | if isinstance(item, list): 21 | result_list.extend(flat(item)) 22 | else: 23 | result_list.append(item) 24 | return result_list 25 | 26 | result = flat(my_list) 27 | print('Input:', my_list) 28 | print('Result:', result) 29 | -------------------------------------------------------------------------------- /Basic-Scripts/forWithList.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | list1 = ['banana','mango','book','table'] 3 | for i in range(len(list1)): 4 | print('He gave me ' + str(i) + ' ' + ' '+ list1[i] +' '+ 'in my birthday') 5 | -------------------------------------------------------------------------------- /Basic-Scripts/for_loop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #for is a looping statement in python 3 | item=['john','cena','johnson','vicky','rock'] 4 | for i in item: 5 | print(item) 6 | -------------------------------------------------------------------------------- /Basic-Scripts/for_loop2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | for i in range(0,10): 4 | i=i+1 5 | print(i) 6 | -------------------------------------------------------------------------------- /Basic-Scripts/for_loop3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #Finding factorial of number using for loop 3 | 4 | n=int(input("\nenter the number:\n")) 5 | f=1 6 | for i in range(1,n): 7 | i=i+1 8 | f=f*i 9 | 10 | print("\nfactorial of number ",n,"is : ",f) 11 | -------------------------------------------------------------------------------- /Basic-Scripts/function_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #function are reusable code in every language 3 | #In python we use 'def' keyword to declare function 4 | 5 | def Print(): #declaretion of function 6 | print("Function in Python Programming!\n") #Body of function 7 | 8 | Print() #Function calling 9 | -------------------------------------------------------------------------------- /Basic-Scripts/function_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | 4 | def Condition(): 5 | a=int(input("enter the number:\n")) 6 | b=int(input("enter second number:\n")) 7 | if a > b: 8 | print("a is greater than b") 9 | else: 10 | print("b is greater than a") 11 | Condition() 12 | 13 | -------------------------------------------------------------------------------- /Basic-Scripts/function_parameter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #function with parameters or arguments 3 | def para(item,item1): #item and item1 are parameters 4 | item2=item+item1 5 | if item2 > 120: 6 | for i in range(5,10): 7 | i=i+1 8 | print(i) 9 | 10 | else: 11 | j=1 12 | while(j<=10): 13 | print(j) 14 | j=j+1 15 | 16 | para(60,90) 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Basic-Scripts/function_parameter_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #Program to find even and odd number with parameterized function 3 | def Even_Odd(n): 4 | if n%2 == 0: 5 | print(n,"is even number\n") 6 | else: 7 | print(n,"is odd number\n") 8 | 9 | Even_Odd(6) 10 | -------------------------------------------------------------------------------- /Basic-Scripts/get_ip_address.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | # return local and public ip address 3 | 4 | import socket 5 | import requests 6 | 7 | def get_local_IP(): 8 | try: 9 | host_name = socket.gethostname() 10 | local_ip = socket.gethostbyname(host_name) 11 | print("Local IP: ", local_ip) 12 | except: 13 | print("Unable to get Local IP") 14 | 15 | 16 | def get_public_IP(): 17 | try: 18 | public_ip = requests.get('http://www.icanhazip.com').content.decode() 19 | print("Public IP: ", public_ip) 20 | except: 21 | print("Unable to get Public IP") 22 | 23 | 24 | get_local_IP() 25 | get_public_IP() 26 | -------------------------------------------------------------------------------- /Basic-Scripts/github_opener.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import pyperclip 4 | 5 | # Install pyperclip module. Linux OS : sudo apt install python3-pyperclip 6 | # otherwise : pip3 install pyperclip 7 | 8 | def github_opener (filename, line_no): 9 | """ 10 | github_opener( filename, line_no ) : 11 | Generates a perma link to the code inside your Github repo which is remote for your current git project. 12 | And copies it to clipboard. 13 | 14 | Parameters: 15 | github_opener ( filename, line_no ) : takes two arguments. 16 | Filename in which the code is and line no which you want to highlight. 17 | eg. github_opener("hello.py", 8) 18 | 19 | Returns: 20 | Perma link copied to clipboard 21 | 22 | """ 23 | 24 | stream = os.popen('git remote -v | grep "origin"') 25 | cmd_output = stream.readline() #cmd_output => origin git@github:username/proj/name.git (fetch) 26 | info = cmd_output.split(":")[1].split(".")[0] #info => username/proj_name 27 | 28 | curr_dir = os.getcwd() 29 | 30 | proj_name = info.split("/")[1] #proj_name 31 | index = curr_dir.find(proj_name) #start index of proj name in current path 32 | perma_link = "https://github.com/" + info + "/blob/master" + curr_dir[(index+len(proj_name)):] + "/" + filename + "/#L" + line_no 33 | pyperclip.copy(perma_link) 34 | print("Link copied!") 35 | 36 | if __name__ == "__main__": 37 | """ 38 | It takes two command line arguments. 39 | Name of the file (Not complete path with directory) in which the desired line of code is present and 40 | the line number to high light. 41 | Eg. 42 | python github_opener.py mode.py 9 43 | output: 44 | Link copied! 45 | (Link => https://github.com/username/proj_name/blob/master/directory/mode.py/#L9) 46 | 47 | 48 | In terminal, navigate to the directory in which the file is present. 49 | 50 | Run command : python github_opener.py filename.xyz 23 51 | 52 | """ 53 | github_opener(sys.argv[1], sys.argv[2]) -------------------------------------------------------------------------------- /Basic-Scripts/guessgameadv.py: -------------------------------------------------------------------------------- 1 | import random 2 | highest = 10 3 | answer = random.randint(1,highest) 4 | print(answer) 5 | guess = 0 6 | print('please guess a number from 1 and {}:'.format(highest)) 7 | while guess != answer: 8 | guess = int(input()) 9 | if guess == answer: 10 | print('well done you did it.') 11 | break 12 | else: 13 | if guess < answer: 14 | print('please guess higher') 15 | else: 16 | print('please guess lower') 17 | -------------------------------------------------------------------------------- /Basic-Scripts/guessinggame.py: -------------------------------------------------------------------------------- 1 | import random 2 | def start(limit, chances): 3 | number = random.randint(1, limit) 4 | win = False 5 | while chances > 0: 6 | guess = int(input()) 7 | if guess == number: 8 | print("HOORAY YOU WON!!!") 9 | win = True 10 | break 11 | elif guess < number: 12 | print("Your guess was too low: Guess a number higher than", guess) 13 | 14 | else: 15 | print("Your guess was too high: Guess a number lower than", guess) 16 | 17 | chances -= 1 18 | 19 | if win is not True: 20 | print("YOU LOSE!!! The number is", number) 21 | 22 | 23 | if __name__ == "__main__": 24 | print("Number guessing game") 25 | limit = int(input("Enter range of number: ")) 26 | chances = int(input("Enter the number of chances: ")) 27 | print("Guess a number (between 1 and your range): ") 28 | start(limit, chances) 29 | -------------------------------------------------------------------------------- /Basic-Scripts/gui-tk.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | 3 | 4 | class Window: 5 | def __init__(self, toplevel): 6 | # create a frame that is a conteiner to widgets 7 | self.frame = tk.Frame(toplevel) 8 | # 'pack' is a geometry manager. there are 3 types: 9 | # 1.pack: tk places the widgets for you, but you can manage a few parameters 10 | # 2.place: you can explicitly define position of the widget in window 11 | # 3.grid: you can place widgets on window in a grid 12 | self.frame.pack() 13 | # create a widget, in this case a label 14 | self.lbl1 = tk.Label(self.frame, text='Click to turn green') 15 | self.lbl1['width'] = 26 16 | self.lbl1['height'] = 3 17 | # paint background color 18 | self.lbl1['bg'] = 'yellow' 19 | self.lbl1.pack(fill=tk.X, padx=10, pady=5) 20 | # create another widget, a button 21 | self.btn = tk.Button(self.frame, text='Click here!') 22 | # a handler that trigger a event 'change_color' when btn is clicked 23 | self.btn.bind("", self.change_color) 24 | self.btn.pack(fill=tk.X, padx=10, pady=5) 25 | 26 | def change_color(self, event): 27 | if self.lbl1['bg'] == 'yellow': 28 | self.lbl1['bg'] = 'green' 29 | self.lbl1['text'] = 'Click to turn yellow' 30 | else: 31 | self.lbl1['bg'] = 'yellow' 32 | self.lbl1['text'] = 'Click to turn green' 33 | 34 | 35 | root = tk.Tk() 36 | Window(root) 37 | root.mainloop() 38 | -------------------------------------------------------------------------------- /Basic-Scripts/hangman.py: -------------------------------------------------------------------------------- 1 | import random 2 | #Sample word list, a file containing words can also be converted into list 3 | world_list = ["ball","account","xerox","laptop","python","Programming","Hangman","mumbai","bangalore"] 4 | #print(world_list) 5 | word = random.choice(world_list) 6 | blanks = ["_" for i in range(len(word))] 7 | word = word.lower() 8 | Dict = {} 9 | for i in range(len(word)): 10 | if word[i] not in Dict: 11 | Dict[word[i]] = [i] 12 | 13 | else: 14 | Dict[word[i]].append(i) 15 | #print(Dict) 16 | print("Let's play Hangman!!\nYou have 7 chances to guess the word") 17 | chances = 7 18 | miss = [] 19 | while chances: 20 | print("Word: "," ".join(blanks)) 21 | ch = input("Guess: ").lower() 22 | if ch in Dict: 23 | list1 = Dict[ch] 24 | for i in list1: 25 | blanks[i] = ch 26 | if blanks.count("_") == 0: 27 | print("Word: "," ".join(blanks)) 28 | print("Yayy!!! You made it!!!!") 29 | break 30 | else: 31 | chances -= 1 32 | print("Wrong choice! You have ",chances," chances!!! ") 33 | miss.append(ch) 34 | print("Misses: ",", ".join(miss)) 35 | 36 | #print(ch) 37 | if not chances: 38 | print("The word is: ",word) 39 | -------------------------------------------------------------------------------- /Basic-Scripts/happy_numbers.py: -------------------------------------------------------------------------------- 1 | # https://www.wikiwand.com/en/Happy_number 2 | # http://mathworld.wolfram.com/HappyNumber.html 3 | 4 | def square(x): 5 | return int(x) * int(x) 6 | 7 | def happy(number): 8 | return sum(map(square, list(str(number)))) 9 | 10 | def is_happy(number): 11 | seen_numbers = set() 12 | while number > 1 and (number not in seen_numbers): 13 | seen_numbers.add(number) 14 | number = happy(number) 15 | return number == 1 16 | 17 | def is_happy2(n): # recursive 18 | return (n == 1 or n > 4 and is_happy2(happy(n))) 19 | -------------------------------------------------------------------------------- /Basic-Scripts/hello.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #first world program 3 | print("Hello World!") 4 | -------------------------------------------------------------------------------- /Basic-Scripts/if_elif.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #if and elif 3 | 4 | var1=int(input("enter first value:\n")) 5 | var2=int(input("enter second value:\n")) 6 | var3=int(input("enter third value:\n")) 7 | 8 | if var1 > var2 & var1 > var3 : 9 | print(var1,"is greater than",var2,"and",var3) 10 | 11 | elif var2 > var1 & var2 > var3 : 12 | print(var2,"is greater than",var1,"and",var3) 13 | 14 | else : 15 | print(var3,"is greater than",var1,"and",var2) 16 | -------------------------------------------------------------------------------- /Basic-Scripts/if_else.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #conditional programming with if else 3 | var1=float(input("enter variable-1 value:\n")) 4 | var2=float(input("enter variable-2 value:\n")) 5 | 6 | add=var1+var2 7 | 8 | if add > 10.0 : 9 | print("output:\n",add) 10 | else: 11 | print("no output:\n") 12 | 13 | -------------------------------------------------------------------------------- /Basic-Scripts/if_else_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #second program with if else 3 | 4 | var1=float(input("enter value var1:\n")) 5 | var2=float(input("enter value var2:\n")) 6 | 7 | if var1 < var2 : 8 | print(var1,"is less than",var2) 9 | else: 10 | print(var2,"is less than",var1) 11 | 12 | -------------------------------------------------------------------------------- /Basic-Scripts/insert_sort.py: -------------------------------------------------------------------------------- 1 | def insert_sort(_list): 2 | for i in range(1, len(_list)): 3 | elm = _list[i] 4 | k = i 5 | while not k <= 0 and _list[k - 1] > elm : 6 | _list[k] = _list[k - 1] 7 | k -= 1 8 | _list[k] = elm 9 | l = _list 10 | return l 11 | -------------------------------------------------------------------------------- /Basic-Scripts/leap_year.py: -------------------------------------------------------------------------------- 1 | def is_leap(year): 2 | 3 | return year % 4 == 0 and (year % 400 == 0 or year % 100 != 0) 4 | 5 | 6 | year = int(input()) 7 | print(is_leap(year)) -------------------------------------------------------------------------------- /Basic-Scripts/letter_counter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #This program will receive an input from the user and count how many time each digit appears 3 | letter_counter={} 4 | 5 | for letter in input("I want to count the letters of: ").lower(): 6 | if letter in letter_counter: 7 | letter_counter[letter] += 1 8 | else: 9 | letter_counter[letter] = 1 10 | 11 | for letter in letter_counter: 12 | print("#" + letter + ":", letter_counter[letter]) -------------------------------------------------------------------------------- /Basic-Scripts/list_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #list in python 3 | 4 | item=['a','b','c',2,3] 5 | new=['ankit','aman','arun',5,6] 6 | 7 | print("list of items:\n",item) 8 | print("list of itemss:\n",new) 9 | 10 | print("list of total item:\n",item+new) 11 | 12 | -------------------------------------------------------------------------------- /Basic-Scripts/list_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #find length of list and some other stuff 3 | 4 | item=['john','elliot','joe',1,5,6] 5 | item1=['wayne','love',10,89,78] 6 | item2=[4,56,8,9,7] 7 | 8 | print("\nFirst list:\n",item) 9 | print("\nsecond list:\n",item1) 10 | print("\nthird list:\n",item2) 11 | 12 | print("\n",len(item),"is a length of first list") 13 | print("\n",len(item1),"is a length of second list") 14 | 15 | print("\n first element of first list is : ",item[0]) 16 | print("\n last element of second list is : ",item1[5-1]) 17 | 18 | print("\nmimimum element in third list : ",min(item2)) 19 | print("\nmaximum element in third list : ",max(item2)) 20 | 21 | print("\nadding a new element in first list 'rock' ") 22 | item.append("rock") 23 | print("\n First list : \n",item) 24 | 25 | # 26 | item1[2]='dsf' 27 | print(item1) 28 | -------------------------------------------------------------------------------- /Basic-Scripts/list_tuple_dict.py: -------------------------------------------------------------------------------- 1 | #first program of list 2 | item1=56 3 | item2="main" 4 | listoftwoitems=[item1,item2] 5 | print("output:\n",listoftwoitems) 6 | 7 | 8 | 9 | #second program 10 | a=[5,6,8] 11 | print("length of list : ",len(a)) 12 | a.append(6) 13 | print("adding new value in list : ",a) 14 | print("maixmum in list : ",max(a)) 15 | print("minimum in list :",min(a)) 16 | a.index(6) 17 | print(a) 18 | 19 | 20 | 21 | #third program of list related to random module 22 | import random 23 | a=list(range(1,16)) 24 | print(a) 25 | random.shuffle(a) 26 | print(a) 27 | random.choice(a) 28 | 29 | 30 | 31 | 32 | #program to tuple 33 | #note tuple can not be changed it is immutable 34 | a=(4,5,8,9,'new','items') 35 | b=(10,8,7,2,'last','thing') 36 | print(a) 37 | 38 | 39 | 40 | 41 | #fisrt program of dictionaries 42 | a={'name':'aman','age':89,'class':10} 43 | print(a) 44 | print(list(a.keys())) 45 | print(list(a.values())) 46 | 47 | 48 | #second program of dictionaries 49 | n={} 50 | n["name"]="aman" 51 | n["profession"]="teacher" 52 | print(n) 53 | -------------------------------------------------------------------------------- /Basic-Scripts/location_ip: -------------------------------------------------------------------------------- 1 | import geocoder 2 | 3 | loc = input("Enter the location:") 4 | g = geocoder.arcgis(loc) 5 | print(g.latlng) 6 | -------------------------------------------------------------------------------- /Basic-Scripts/magic8Ball.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | # return statement 3 | import random 4 | 5 | 6 | possibleAnswer = [ 7 | 'It is certain', 8 | 'It is decidedly so', 9 | 'Yes', 10 | 'Reply hazy try again', 11 | 'Ask again later', 12 | 'Concentrate and ask again', 13 | 'My reply is no', 14 | 'Outlook not so good', 15 | 'Very doubtful' 16 | ] 17 | 18 | def getAnswer(answerIndex): 19 | return possibleAnswer[answerIndex] 20 | 21 | 22 | r = random.randint(0, 8) 23 | fortune = getAnswer(r) 24 | print(fortune) 25 | -------------------------------------------------------------------------------- /Basic-Scripts/magic_square.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Tue Aug 18 11:24:15 2020 4 | 5 | @author: Gulshan 6 | """ 7 | ''' 8 | 9 | What is Magic Square? 10 | => a square divided into smaller squares each containing a number, 11 | such that the figures in each vertical, horizontal, and diagonal row add up to the same value. 12 | 13 | Example: 14 | 2 7 6 15 | 9 5 1 16 | 4 3 8 17 | The sum of each row/column/diagonal is: 15.0 18 | 19 | ''' 20 | 21 | # Function to create Magic Square 22 | def magic_square(n): 23 | 24 | magicSquare = [] 25 | for i in range(n): 26 | listt = [] 27 | for j in range(n): 28 | listt.append(0) 29 | magicSquare.append(listt) 30 | 31 | i = n//2 32 | j = n-1 33 | 34 | num = n*n 35 | count = 1 36 | 37 | while(count<=num): 38 | if(i==-1 and j==n): #condition 4 39 | j = n-2 40 | i = 0 41 | else: 42 | if(j==n): # column value is exceeding 43 | j = 0 44 | 45 | if(i<0): # row is becoming -1 46 | i=n-1 47 | 48 | if(magicSquare[i][j]!=0): 49 | j = j-2 50 | i = i+1 51 | continue 52 | 53 | else: 54 | magicSquare[i][j] = count 55 | count+=1 56 | 57 | i = i-1 58 | j = j+1 #condition 1 59 | 60 | for i in range(n): 61 | for j in range(n): 62 | print(magicSquare[i][j], end=" ") 63 | print() 64 | 65 | print("The sum of each row/column/diagonal is: "+str(n*(n**2+1)/2)) 66 | 67 | # Main Function for Magic Square 68 | if __name__ == '__main__': 69 | n = int(input("Enter Number To Generate Magic Square")) 70 | magic_square(n) 71 | 72 | -------------------------------------------------------------------------------- /Basic-Scripts/math_expression.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #program of mathematical expression 3 | 4 | x=int(input("Give your first input:\n")) 5 | y=float(input("Give your second input:\n")) 6 | 7 | print("sum of numbers:\n",x+y) 8 | print("substract of numbers:\n",x-y) 9 | print("multiplication of numbers:\n",x*y) 10 | print("division of numbers:\n",x/y) 11 | print("modules:\n",x%y) 12 | -------------------------------------------------------------------------------- /Basic-Scripts/math_func.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | #square root 3 | # import math 4 | from math import * #with this form of import statement,calls functions in math 5 | a=int(input("enter first number\n")) #will not need the math prefix dot 6 | b=int(input("enter second number\n")) 7 | 8 | def func(): 9 | if a > b : 10 | print(sqrt(a)) #like this 11 | ## print(math.sqrt(a)) 12 | else: 13 | print(sqrt(b)) 14 | ## print(math.sqrt(b)) 15 | func() 16 | 17 | -------------------------------------------------------------------------------- /Basic-Scripts/maxBetween2NumbersWithoutIF.py: -------------------------------------------------------------------------------- 1 | def maxNumber( num1, num2 ): 2 | ''' 3 | The brief: 4 | As input we have 2 int numbers. To pick the greater without if-else clauses we have 5 | to made a simple account. 6 | - To begin we have to calculate sum the two numbers; 7 | - Then we plus the result with the absolute value of the difference between num1 and num2; 8 | - Adding the absolute value of difference to the result, we've completed the smallest number to 9 | reach in the greater value; 10 | - The the total value of the sum is (num1+num2)+(the complement to the smaller be the equal to the greater), 11 | and this is equal to the greater two times; 12 | - At least we return the floor division of the sum by 2 13 | ''' 14 | return ( num1 + num2 + abs( num1 - num2 ) ) // 2 15 | 16 | # Now you have to construct the tests. Let's Hack. :) -------------------------------------------------------------------------------- /Basic-Scripts/merge_sort.py: -------------------------------------------------------------------------------- 1 | def merge_sort(lst_main): 2 | if len(lst_main) <= 1: 3 | return lst_main 4 | else: 5 | mid = len(lst_main) // 2 6 | 7 | l = merge_sort(lst_main[:mid]) 8 | r = merge_sort(lst_main[mid:]) 9 | 10 | return merge(l, r) 11 | 12 | 13 | 14 | def merge(lst_left, lst_right): 15 | lst_ord = [] 16 | p_left = 0 17 | p_right = 0 18 | 19 | while p_left < len(lst_left) and p_right < len(lst_right): 20 | if lst_left[p_left] > lst_right[p_right]: 21 | lst_ord.append(lst_right[p_right]) 22 | p_right += 1 23 | else: 24 | lst_ord.append(lst_left[p_left]) 25 | p_left += 1 26 | 27 | for i in range(p_left, len(lst_left)): 28 | lst_ord.append(lst_left[i]) 29 | 30 | for i in range(p_right, len(lst_right)): 31 | lst_ord.append(lst_right[i]) 32 | 33 | return lst_ord 34 | 35 | import random 36 | 37 | def main(): 38 | lst = [] 39 | 40 | for i in range(100): 41 | lst.append(random.randrange(9)) 42 | 43 | print(merge_sort(lst)) 44 | 45 | return 0 46 | 47 | if __name__ == '__main__': 48 | main() -------------------------------------------------------------------------------- /Basic-Scripts/myPets.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | mypets = ['Zophie','Poka','fat-tail'] 4 | 5 | name = input('Enter pet name: ') 6 | 7 | if name not in mypets: 8 | print('I dont have a pet name "%s"' % name ) 9 | else: 10 | print(name + ', is my pet') 11 | -------------------------------------------------------------------------------- /Basic-Scripts/odd_even.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | #program to find odd and even number 3 | 4 | digit=int(input("Give your input:\n")) 5 | 6 | if digit%2 == 0 : 7 | print(digit,"is odd") 8 | 9 | else : 10 | print(digit,"is even") 11 | -------------------------------------------------------------------------------- /Basic-Scripts/palindrome.py: -------------------------------------------------------------------------------- 1 | n=int(input("Enter number:")) 2 | temp=n 3 | rev=0 4 | while(n>0): 5 | dig=n%10 6 | rev=rev*10+dig 7 | n=n//10 8 | if(temp==rev): 9 | print("The number is a palindrome!") 10 | else: 11 | print("The number is not a palindrome!") -------------------------------------------------------------------------------- /Basic-Scripts/password_checker.py: -------------------------------------------------------------------------------- 1 | # Password-checker 2 | 3 | #This program can help us to find how many times a password has been used,either on anonymous or your own used sites. 4 | 5 | #It will take help of requests,hashlib and sys modules 6 | 7 | #You need to install pip3 into your machine to be able to use this code. 8 | 9 | 10 | 11 | import requests 12 | import hashlib 13 | import sys 14 | 15 | def request_api_data(query_char): 16 | url = 'https://api.pwnedpasswords.com/range/' + query_char 17 | res = requests.get(url) 18 | if res.status_code != 200: 19 | raise RuntimeError(f': {res.status_code}, got some eror,please check API') 20 | return res 21 | 22 | def get_password_leaks_count(hashes, hash_to_check): 23 | hashes = (line.split(':') for line in hashes.text.splitlines()) 24 | for h, count in hashes: 25 | if h == hash_to_check: 26 | return count 27 | return 0 28 | 29 | def pwned_api_check(password): 30 | sha1password = hashlib.sha1(password.encode('utf-8')).hexdigest().upper() 31 | first5_char, tail = sha1password[:5], sha1password[5:] 32 | response = request_api_data(first5_char) 33 | return get_password_leaks_count(response, tail) 34 | 35 | def main(args): 36 | for password in args: 37 | count = pwned_api_check(password) 38 | if count: 39 | print(f'{password} was found {count} times... you should change your password right now!') 40 | else: 41 | print(f'{password} was not found,very good password.') 42 | return 'done!' 43 | 44 | if __name__ == '__main__': 45 | sys.exit(main(sys.argv[1:])) 46 | -------------------------------------------------------------------------------- /Basic-Scripts/picnicTable.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | def printPicnic(itemsDict,leftWidth,rightWidth): 3 | print('PICNIC ITEMS'.center(leftWidth + rightWidth,'-')) 4 | for k,v in itemsDict.items(): 5 | print(k.ljust(leftWidth,'.') + str(v).rjust(rightWidth)) 6 | 7 | picnicItems = {'sandwiches': 4, 'apples' : 12, 'cups' : 4, 'cookies' : 8000, 'table' : 4} 8 | printPicnic(picnicItems,12,5) 9 | printPicnic(picnicItems,20,6) 10 | -------------------------------------------------------------------------------- /Basic-Scripts/prime_numbers.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Created on Oct 15, 2019 3 | 4 | @author: Big 5 | ''' 6 | n=int(input("write a number >0:")) 7 | ok=1 8 | if(n==0 or n==1): 9 | ok=0 10 | else: 11 | if(n%2==0): 12 | if(n!=2): 13 | ok=0 14 | else: 15 | d=2 16 | while(d<=n//2): 17 | if(n%d==0): 18 | ok=0 19 | break 20 | if(d==2): 21 | d=3 22 | else: 23 | d+=2 24 | if(ok==1): 25 | print("prime") 26 | else: 27 | print("!prime") -------------------------------------------------------------------------------- /Basic-Scripts/pyperClip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import pyperclip 3 | a = pyperclip.copy('Hello world!') 4 | b = pyperclip.paste() 5 | print(b) 6 | -------------------------------------------------------------------------------- /Basic-Scripts/quad_equation.py: -------------------------------------------------------------------------------- 1 | # Python Program to find roots of a Quadratic Equation 2 | # Solve the quadratic equation ax**2 + bx + c = 0 3 | 4 | 5 | import math # import complex math module 6 | 7 | 8 | def findRoots(a, b, c): 9 | """ 10 | If a is 0 then equation is not quadratic but linear, 11 | So if user enters value of a as zero then its invalid. 12 | """ 13 | if a == 0: 14 | print("Invalid") 15 | return -1 16 | discriminant = (b * b) - (4 * a * c) # calculating value of discriminant 17 | """ 18 | Now below we check for various condition, i.e 19 | Is discriminant greater than, equals to or less than 0. 20 | Each condition has its own different roots. 21 | """ 22 | if(discriminant > 0): 23 | root_1 = (-b + math.sqrt(discriminant) / (2 * a)) 24 | root_2 = (-b - math.sqrt(discriminant) / (2 * a)) 25 | print("Two Distinct Real Roots Exists: ") 26 | print("root1 = %.2f and root2 = %.2f" % (root_1, root_2)) 27 | elif(discriminant == 0): 28 | root_1 = root_2 = -b / (2 * a) 29 | print("Two Equal and Real Roots Exists: ") 30 | print("root1 = %.2f and root2 = %.2f" % (root_1, root_2)) 31 | elif(discriminant < 0): 32 | root_1 = root_2 = -b / (2 * a) 33 | imaginary = math.sqrt(-discriminant) / (2 * a) 34 | print("Two Distinct Complex Roots Exists: ") 35 | print("r1=%.2f+%.2f and r2=%.2f-%.2f" % (root_1, imaginary, root_2, imaginary)) 36 | 37 | # Main Program 38 | if __name__ == "__main__": 39 | a = float(input("Please Enter a Value of a Quadratic Equation : ")) 40 | b = float(input("Please Enter b Value of a Quadratic Equation : ")) 41 | c = float(input("Please Enter c Value of a Quadratic Equation : ")) 42 | 43 | print(findRoots(a, b, c)) 44 | -------------------------------------------------------------------------------- /Basic-Scripts/rand_range.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | # return random number in range 3 | import random 4 | import sys 5 | 6 | print('----------------------------------------') 7 | try: 8 | rand_min, rand_max, n = int(sys.argv[1]), int(sys.argv[2]), ( int(sys.argv[3]) if len(sys.argv) > 3 else 1 ) 9 | 10 | random_ints = [] 11 | 12 | if n == 1: 13 | print('random number:', random.randint(rand_min, rand_max)) 14 | else: 15 | for i in range(n): 16 | random_int = random.randint(rand_min, rand_max) 17 | print('\trandom number:', random_int) 18 | random_ints.append(random_int) 19 | 20 | print('----------------------------------------') 21 | print(f'min: {min(random_ints)}, max: {max(random_ints)}, avg: {sum(random_ints)/len(random_ints)}') 22 | 23 | except ValueError: 24 | print('only number like value are valid for min, max') 25 | 26 | except IndexError: 27 | print(''' 28 | No min or max number was supplied 29 | rand_range.py 30 | ''') 31 | -------------------------------------------------------------------------------- /Basic-Scripts/random.py: -------------------------------------------------------------------------------- 1 | # Python code for 1-D random walk. 2 | import random 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | 7 | prob = [0.05, 0.95] 8 | 9 | 10 | start = 2 11 | positions = [start] 12 | 13 | 14 | rr = np.random.random(1000) 15 | downp = rr < prob[0] 16 | upp = rr > prob[1] 17 | 18 | 19 | for idownp, iupp in zip(downp, upp): 20 | down = idownp and positions[-1] > 1 21 | up = iupp and positions[-1] < 4 22 | positions.append(positions[-1] - down + up) 23 | 24 | 25 | plt.plot(positions) 26 | plt.show() 27 | -------------------------------------------------------------------------------- /Basic-Scripts/random_password.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | 4 | def get_random_password(): 5 | random_source = string.ascii_letters + string.digits 6 | password = random.choice(string.ascii_lowercase) 7 | password += random.choice(string.ascii_uppercase) 8 | password += random.choice(string.digits) 9 | 10 | 11 | for index in range(6): 12 | password += random.choice(random_source) 13 | 14 | password_list = list(password) 15 | random.SystemRandom().shuffle(password_list) 16 | password = ''.join(password_list) 17 | return password 18 | 19 | print(" Random Password is ", get_random_password()) 20 | 21 | -------------------------------------------------------------------------------- /Basic-Scripts/recursion.py: -------------------------------------------------------------------------------- 1 | # "Towers of Hanoi" Game 2 | # A recursive solution almost forces itself on the programmer, 3 | # while the iterative solution of the game is hard to find and to grasp. 4 | # 5 | # "Recursion" 6 | # Recursion is a method of programming or coding a problem, 7 | # in which a function calls itself one or more times in its body. 8 | # Usually, it is returning the return value of this function call. 9 | # If a function definition satisfies the condition of recursion, we call this function a recursive function. 10 | 11 | 12 | def hanoi(n, source, helper, target): 13 | if n > 0: 14 | # move tower of size n-1 to helper: 15 | hanoi(n-1, source, target, helper) 16 | # move disk from source to target: 17 | if source: 18 | target.append(source.pop()) 19 | # move tower of size n-1 from helper to target: 20 | hanoi(n-1, helper, source, target) 21 | 22 | if __name__ == "__main__": 23 | height = int(input("Enter the height of the tower: ")) 24 | source = [disk for disk in range(1, height+1)] 25 | helper = [] 26 | target = [] 27 | print("Before calling the recursive function...") 28 | print("Source tower: ", str(source)) 29 | print("Target tower: ", str(target)) 30 | 31 | # call the hanoi function to start recursie execution 32 | hanoi(height, source, helper, target) 33 | print("After recursive calls...") 34 | print("Source tower: ", str(source)) 35 | print("Target tower: ", str(target)) 36 | -------------------------------------------------------------------------------- /Basic-Scripts/reverse.py: -------------------------------------------------------------------------------- 1 | message = input("Enter the string to reverse:\t") 2 | 3 | message_reverse = message[::-1] 4 | 5 | print("The reversed string is \n") 6 | print(message_reverse) 7 | -------------------------------------------------------------------------------- /Basic-Scripts/scrap_quotes.py: -------------------------------------------------------------------------------- 1 | from bs4 import BeautifulSoup 2 | import requests 3 | import json 4 | base_url="https://www.goodreads.com/quotes/tag/{0}?page={1}" # the url of the site from where quotes 5 | #will be scrapped emotion and page number will be inserted later 6 | 7 | def process(content,emotion): # function to clean the content of the webpage 8 | soup=BeautifulSoup(content,features="html5lib") 9 | quotes_div=soup.find_all("div",attrs={"class","quote"}) 10 | quotes=[] 11 | for div in quotes_div: 12 | q_text=div.find("div",attrs={"class","quoteText"}) 13 | quote=(q_text.text.strip().split('\n')[0]) 14 | author=q_text.find("span",attrs={"class","authorOrTitle"}).text.strip() 15 | q_dict={"quote":quote,"author":author,"emotion":emotion} 16 | quotes.append(q_dict) 17 | return quotes 18 | 19 | emotions=['friend','sad'] # you can select any other emotion 20 | quotes=[] 21 | for emotion in emotions: 22 | for index in range(1,5): # here 5 pages have been taken 23 | final_url=base_url.format(emotion,index) 24 | page=requests.get(final_url) 25 | content=page.text 26 | quotes+=process(content,emotion) 27 | 28 | with open('quote.json','w') as file: # dump the quotes in json file 29 | json.dump(quotes,file) -------------------------------------------------------------------------------- /Basic-Scripts/secure your password.py: -------------------------------------------------------------------------------- 1 | sym = { 2 | 'a' : '!!', 3 | 'b' : '@', 4 | 'c' : '#', 5 | 'd' : '$', 6 | 'e' : '^', 7 | 'f' : '}', 8 | 'g' : ']', 9 | 'h' : ')', 10 | 'i' : '*', 11 | 'j' : '=', 12 | 'k' : '+', 13 | 'l' : '-', 14 | 'm' : '_', 15 | 'n' : '>', 16 | 'o' : '<', 17 | 'p' : '.', 18 | 'q' : '%', 19 | 'r' : '&', 20 | 's' : '(', 21 | 't' : '{', 22 | 'u' : '[', 23 | 'x' : '?', 24 | 'y' : ',', 25 | 'z' : '|', 26 | } 27 | inp = 'alphabet' 28 | password = '' 29 | 30 | for i in inp: 31 | for key, val in sym.items(): 32 | if i in key: 33 | password = password + val 34 | print("Name you entered : ", inp) 35 | print("Password : ", password) -------------------------------------------------------------------------------- /Basic-Scripts/selection_sort.py: -------------------------------------------------------------------------------- 1 | def selecsort(lst): 2 | ''' It takes a list as input from the user and returns it's sorted version. ''' 3 | for i in range(len(lst)): 4 | minpos=i 5 | for j in range(i,len(lst)): 6 | if lst[j]>>>", lst_to_multiply) 23 | new_lst.insert(i, reduce((lambda x,y: x * y), lst_to_multiply)) 24 | 25 | print("NEW_LST", new_lst) 26 | -------------------------------------------------------------------------------- /Basic-Scripts/sum_of_items_list.py: -------------------------------------------------------------------------------- 1 | def sum_of_elements(user_list): #function definition 2 | 3 | '''Function that prints sum of elements in a list 4 | params: user_list 5 | returns: None 6 | ''' 7 | answer = 0 8 | for item in user_list: 9 | answer += item #stores the sum of elements 10 | print("Sum of elements in the list:",answer) 11 | 12 | 13 | 14 | if __name__ == "__main__": 15 | user_list = [] 16 | # number of elemetns as input 17 | num = int(input("Enter number of elements:")) 18 | 19 | # iterating till the range 20 | print("Enter the elements:") 21 | for index in range(0, num): 22 | elements = int(input()) 23 | user_list.append(elements) # adding the element 24 | 25 | sum_of_elements(user_list) #function calling 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Basic-Scripts/table.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | #logarithms table 3 | import math 4 | def logarithm(): 5 | x = 1.0 6 | while x < 10.0: 7 | print(x,'\t',math.log(x)) 8 | x = x + 1.0 9 | 10 | logarithm() 11 | -------------------------------------------------------------------------------- /Basic-Scripts/tic-tac-toe.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Basic-Scripts/tic-tac-toe.py -------------------------------------------------------------------------------- /Basic-Scripts/time.py: -------------------------------------------------------------------------------- 1 | import datetime as DT 2 | 3 | time = DT.datetime.utcnow() 4 | time = time.strftime("Year : %Y | Month : %B | WeekDay : %A | Hour : %H %p | Minute : %M | Second : %S ") 5 | print(time) 6 | -------------------------------------------------------------------------------- /Basic-Scripts/towerofhanoi.py: -------------------------------------------------------------------------------- 1 | def TowerofHanoi(n,from_rod,to_rod,middle_rod): 2 | if n==1: 3 | print("Move disk 1 from",from_rod,"to",to_rod) 4 | return 5 | TowerofHanoi(n-1,from_rod,middle_rod,to_rod) 6 | print("Move disk",n,"from",from_rod,"to",to_rod) 7 | TowerofHanoi(n-1,middle_rod,to_rod,from_rod) 8 | 9 | 10 | n=int(input("Enter number of disks:")) 11 | TowerofHanoi(n,'A','C','B') -------------------------------------------------------------------------------- /Basic-Scripts/tuple_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #Tuple in python 3 | 4 | item=('john',12,3,5,'joe') 5 | item1=('rony',1,2,3,'archer') 6 | item2=('abhi','arun','karan','shubham') 7 | 8 | print(item) 9 | print(item+item1+item2) 10 | 11 | 12 | -------------------------------------------------------------------------------- /Basic-Scripts/tuple_2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #Tuple is similer to list but only difference it is immutable 3 | item=('john','elliot','warner',1,23,5) 4 | item1=('varun','aldersion',9,8,6) 5 | item2=(5,10,20,80,90,1222) 6 | 7 | print("\nElement of first tuple:\n",item) 8 | print("\nElement of second tuple:\n",item1) 9 | print("\nElement of third tuple:\n",item2) 10 | 11 | #functions and operations in tuple similer to list 12 | 13 | print("\n length of first tuple : ",len(item)) 14 | print("\n length of second tuple : ",len(item1)) 15 | print("\n length of third tuple : ",len(item2)) 16 | 17 | print("\n maximum in third tuple : ",max(item2)) 18 | print("\n minimum in third tuple : ",min(item2)) 19 | 20 | #only difference between tuple and list that element of tuple can not be modified 21 | item[0]='arun' 22 | print(item) 23 | 24 | item1.append('war') 25 | print(item1) 26 | -------------------------------------------------------------------------------- /Basic-Scripts/validateInput.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | while True: 3 | print('Enter your age:') 4 | age = input() 5 | if age.isdecimal(): 6 | break 7 | print('Please enter the number of your age!') 8 | 9 | while True: 10 | print('Select a new password(letter and numbers)') 11 | password = input() 12 | if password.isalnum(): 13 | break 14 | print('Password can on;y have letters & number!') 15 | -------------------------------------------------------------------------------- /Basic-Scripts/watermark_pdf.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This script helps to add water mark to any PDF's 3 | which can have single page to multiple pages using PyPDF2 module 4 | ''' 5 | ''' 6 | Intsall module using command 'pip install PyPDF2' 7 | ''' 8 | import PyPDF2 9 | 10 | SOURCE_PDF = "" 11 | WATERMARK_PDF = "< PROVIDE THE WATERMARK PDF PATH HERE >" 12 | DESTINATION_PDF = "< PROVIDE THE DESTINATION PATH HERE FOR STORING FINAL PDF >" 13 | 14 | # Initializing PDF file reader object for Source PDF 15 | pdf_file_reader = PyPDF2.PdfFileReader(open(SOURCE_PDF,'rb')) 16 | 17 | # Initializing Water mark PDF file reader object which has only Water mark in first page 18 | watermark_file_reader = PyPDF2.PdfFileReader(open(WATERMARK_PDF,'rb')) 19 | 20 | watermark = watermark_file_reader.getPage(0) #To get first page of the PDF which has water mark 21 | 22 | writer = PyPDF2.PdfFileWriter() #Initilaizes PDF writer object 23 | 24 | for each_page in range(pdf_file_reader.getNumPages()): 25 | page = pdf_file_reader.getPage(each_page) # To get each page in the PDF 26 | page.mergePage(watermark) # Merges/Adds the water mark to each page 27 | writer.addPage(page) # Writes the page to writer object 28 | 29 | with open(DESTINATION_PDF,'wb') as file: 30 | writer.write(file) # Final pdf with water mark is stored in destination path 31 | -------------------------------------------------------------------------------- /Basic-Scripts/while1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | item=1 4 | while(item<=10): 5 | print(item) 6 | item=item+1 7 | -------------------------------------------------------------------------------- /Basic-Scripts/while_loop2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #Factorial program using while loop 3 | 4 | n=int(input("\nEnter the number:\n")) 5 | f=1 6 | 7 | i=1 8 | while(i<=n): 9 | f=f*i 10 | i=i+1 11 | 12 | print("\n factorial of number",n,"is:",f) 13 | -------------------------------------------------------------------------------- /Basic-Scripts/word_encrypt.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | 3 | input_word = input("Enter the word you want to encrypt: ") 4 | 5 | hashed_input = hashlib.sha256(input_word.encode()) 6 | 7 | out_hash = hashed_input.hexdigest() 8 | 9 | print(out_hash) -------------------------------------------------------------------------------- /Basic-Scripts/yourname.py: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/python3 2 | name = '' 3 | while name != 'your name': 4 | print('Plese type your name.') 5 | name = input() 6 | 7 | print('Thank you!') 8 | -------------------------------------------------------------------------------- /Basic-Scripts/zeroDivide.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #exception handling program 3 | def spam(divideBy): 4 | try: 5 | return(42/divideBy) 6 | except ZeroDivisionError: 7 | print('Error: Invalid argument') 8 | 9 | print(spam(2)) 10 | print(spam(12)) 11 | print(spam(0)) 12 | print(spam(1)) 13 | 14 | -------------------------------------------------------------------------------- /Calculator_GUI/Readme.md: -------------------------------------------------------------------------------- 1 | # Calculator using Tkinter 2 | - Tkinter is a Python binding to the Tk GUI toolkit. It is the standard Python interface to the Tk GUI toolkit, and is Python's de facto standard GUI. 3 | 4 | - In the file calculator.py we have written script for a simple calculator which is more user friendly because of User Interface. 5 | 6 | - To run the calculator in cmd, first command the directory to the file then 7 | 8 | ```bash 9 | python run calculator.py 10 | ``` 11 | 12 | 13 | -------------------------------------------------------------------------------- /Calculator_GUI/calculator_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Calculator_GUI/calculator_.png -------------------------------------------------------------------------------- /Chat example with socket lib/client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | 4 | def Main(): 5 | host = 'localhost' 6 | port = 1234 7 | 8 | my_Socket = socket.socket() 9 | my_Socket.connect((host, port)) 10 | 11 | print("Connected! {}:{}".format(host, port)) 12 | 13 | message = input(" -> ") 14 | print("Waiting Server...") 15 | 16 | while message != 'q': 17 | my_Socket.send(message.encode()) 18 | data = my_Socket.recv(1024).decode() 19 | 20 | print('Server: ' + data) 21 | 22 | message = input(" -> ") 23 | print("Waiting Server...") 24 | 25 | my_Socket.close() 26 | 27 | 28 | if __name__ == '__main__': 29 | Main() -------------------------------------------------------------------------------- /Chat example with socket lib/server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import time 3 | 4 | 5 | def Main(): 6 | host = "localhost" 7 | port = 1234 8 | 9 | my_Socket = socket.socket() 10 | my_Socket.bind((host, port)) 11 | 12 | my_Socket.listen(1) 13 | conn, addr = my_Socket.accept() 14 | print("Connection from: " + str(addr)) 15 | while True: 16 | while True: # this line, if the client closed the connection, it waits for new connections. 17 | try: 18 | data = str(conn.recv(1024).decode()) 19 | print("Client: " + data) 20 | break 21 | except ConnectionResetError: 22 | time.sleep(1) 23 | conn, addr = my_Socket.accept() 24 | print("Connection from: " + str(addr)) 25 | if data == "q": 26 | break 27 | else: 28 | message = input(" -> ") 29 | print("Waiting Client...") 30 | conn.send(message.encode()) 31 | conn.close() 32 | 33 | 34 | if __name__ == '__main__': 35 | Main() -------------------------------------------------------------------------------- /Contribution.md: -------------------------------------------------------------------------------- 1 | # contribution 2 | If this is your first time to open source contribution in python So that I have created this repo for all the you to start contributing. 3 | 4 | # How to contribute! 5 | 6 | ## Steps: 7 | - First commment on the issue in which you want to work upon. 8 | - Issue-1 : https://github.com/ankitdobhal/Awesome-Python-Scripts/issues/91 9 | - Issue-2 : https://github.com/ankitdobhal/Awesome-Python-Scripts/issues/92 10 | - Issue-3 : https://github.com/ankitdobhal/Awesome-Python-Scripts/issues/93 11 | - Issue-4 : https://github.com/ankitdobhal/Awesome-Python-Scripts/issues/94 12 | 13 | - Fork the [repository](https://github.com/ankitdobhal/Awesome-Python-Scripts) 14 | 15 | - Clone the fork [repo](https://github.com/ankitdobhal/Awesome-Python-Scripts) 16 | - git clone https://github.com/ankitdobhal/Awesome-Python-Scripts 17 | 18 | - git clone https://github.com//Awesome-Python-Scripts 19 | - Create new branch 20 | - git checkout -b 21 | 22 | - Add Scripts related to your respective issues. 23 | - git add 24 | 25 | - Add a commit message ! 26 | - git commit -a -m "" 27 | - Push changes 28 | - git push origin 29 | 30 | 31 | - Push changes 32 | - git push -u origin 33 | 34 | - Create pull requests 35 | - [Try to Mention the related issue for your PR] 36 | -------------------------------------------------------------------------------- /Image-Processing/Basic_OpenCV/README.md: -------------------------------------------------------------------------------- 1 | # Image Processing 2 | 3 | Image Processing is most commonly termed as 'Digital Image Processing' and the domain in which it is frequently used is 'Computer Vision'. 4 | Don't be confused - we are going to talk about both of these terms and how they connect. 5 | Both Image Processing algorithms and Computer Vision (CV) algorithms take an image as input; however, in image processing, 6 | the output is also an image, whereas in computer vision the output can be some features/information about the image. 7 | 8 | ## OpenCV 9 | 10 | ![](https://logodix.com/logo/1989939.png) 11 | 12 | ## Installation 13 | 14 | ### Windows 15 | 16 | $ pip install opencv-python 17 | ### MacOS 18 | $ brew install opencv3 --with-contrib --with-python3 19 | ### Linux 20 | $ sudo apt-get install libopencv-dev python-opencv 21 | 22 | -------------------------------------------------------------------------------- /Image-Processing/Basic_OpenCV/rose.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Basic_OpenCV/rose.jpg -------------------------------------------------------------------------------- /Image-Processing/Canny Edge Detection/CannyEdgeDetection.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | from matplotlib import pyplot as plt 5 | 6 | img = cv2.imread("messi5.jpg", cv2.IMREAD_GRAYSCALE ) 7 | lap = cv2.Laplacian(img, cv2.CV_64F, ksize = 1) 8 | lap = np.uint8(np.absolute(lap)) 9 | sobelX = cv2.Sobel(img, cv2.CV_64F, 1, 0) 10 | sobelY = cv2.Sobel(img, cv2.CV_64F, 0, 1) 11 | canny = cv2.Canny(img, 100, 200) 12 | 13 | sobelX = np.uint8(np.absolute(sobelX)) 14 | sobelY = np.uint8(np.absolute(sobelY)) 15 | 16 | sobelCombined = cv2.bitwise_or(sobelX, sobelY) 17 | 18 | titles = ['images','Laplacian', 'SobelX', 'SobelY', 'sobelCombined', 'Canny'] 19 | images = [img, lap, sobelX, sobelY, sobelCombined, canny] 20 | 21 | for i in range(6): 22 | plt.subplot(2, 3, i+1), plt.imshow(images[i], 'gray') 23 | plt.title(titles[i]) 24 | plt.xticks([]), plt.yticks([]) 25 | 26 | plt.show() -------------------------------------------------------------------------------- /Image-Processing/Canny Edge Detection/Images/glimpse all result.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Canny Edge Detection/Images/glimpse all result.JPG -------------------------------------------------------------------------------- /Image-Processing/Canny Edge Detection/Images/input image.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Canny Edge Detection/Images/input image.JPG -------------------------------------------------------------------------------- /Image-Processing/Canny Edge Detection/Images/pic1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Canny Edge Detection/Images/pic1.JPG -------------------------------------------------------------------------------- /Image-Processing/Canny Edge Detection/Images/pic2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Canny Edge Detection/Images/pic2.JPG -------------------------------------------------------------------------------- /Image-Processing/Canny Edge Detection/Images/res1pic1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Canny Edge Detection/Images/res1pic1.JPG -------------------------------------------------------------------------------- /Image-Processing/Canny Edge Detection/Images/res2pic2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Canny Edge Detection/Images/res2pic2.JPG -------------------------------------------------------------------------------- /Image-Processing/Canny Edge Detection/Images/res3sudoku.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Canny Edge Detection/Images/res3sudoku.JPG -------------------------------------------------------------------------------- /Image-Processing/Canny Edge Detection/Images/tograyscale.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Canny Edge Detection/Images/tograyscale.JPG -------------------------------------------------------------------------------- /Image-Processing/Car_detection/README.md: -------------------------------------------------------------------------------- 1 | # Image Processing 2 | 3 | Image Processing is most commonly termed as 'Digital Image Processing' and the domain in which it is frequently used is 'Computer Vision'. 4 | Don't be confused - we are going to talk about both of these terms and how they connect. 5 | Both Image Processing algorithms and Computer Vision (CV) algorithms take an image as input; however, in image processing, 6 | the output is also an image, whereas in computer vision the output can be some features/information about the image. 7 | 8 | ## OpenCV 9 | 10 | ![](https://logodix.com/logo/1989939.png) 11 | 12 | ## Installation 13 | 14 | ### Windows 15 | 16 | $ pip install opencv-python 17 | ### MacOS 18 | $ brew install opencv3 --with-contrib --with-python3 19 | ### Linux 20 | $ sudo apt-get install libopencv-dev python-opencv 21 | -------------------------------------------------------------------------------- /Image-Processing/Cartoonify Image/Cartoonify.py: -------------------------------------------------------------------------------- 1 | # Importing Libraries 2 | import cv2 3 | import numpy as np 4 | from skimage import io 5 | 6 | # Class Defination 7 | class Cartoon: 8 | def __init__(self): 9 | img = io.imread("images/sunset.jpg") 10 | # 1) Edges Image 11 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 12 | gray = cv2.medianBlur(gray, 5) 13 | edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 9, 7) 14 | 15 | # 2) Color Image 16 | color = cv2.bilateralFilter(img, 10, 300, 300) 17 | RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 18 | 19 | # 3) Cartoon Image 20 | cartoon = cv2.bitwise_and(color, color, mask=edges) 21 | cartoon_img = cv2.cvtColor(cartoon, cv2.COLOR_BGR2RGB) 22 | 23 | # Re-sizeing Image 24 | resize = cv2.resize(RGB_img, (600, 450)) 25 | resize2 = cv2.resize(cartoon_img, (600, 450)) 26 | self.resize = resize 27 | self.resize2 = resize2 28 | 29 | # Displaying Image 30 | # Creating an object of class Cartoon 31 | c1 = Cartoon() 32 | c1.resize 33 | c1.resize2 34 | cv2.imshow("Original_Image", c1.resize) 35 | cv2.imshow("Cartoonified_Image", c1.resize2) 36 | cv2.waitKey(0) 37 | cv2.destroyAllWindows() 38 | -------------------------------------------------------------------------------- /Image-Processing/Cartoonify Image/README.md: -------------------------------------------------------------------------------- 1 |

Cartoonify Image

2 | 3 | The code converts your original image i.e. the image which you have given as input, to cartoonified image.
4 | When you run Cartoonify.py, both the input image and output image will be displayed.
5 | It can be further implemented for pencil-sketch, color-pencil-sketch, water-color image, sepia effect, oldifying, etc. 6 | 7 |

Results:

8 | 9 |

Original Image

10 |

11 |

12 | 13 |

Cartoonified Image

14 |

15 |

16 | -------------------------------------------------------------------------------- /Image-Processing/Cartoonify Image/images/Cartoonified Image.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Cartoonify Image/images/Cartoonified Image.PNG -------------------------------------------------------------------------------- /Image-Processing/Cartoonify Image/images/Original Image.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Cartoonify Image/images/Original Image.PNG -------------------------------------------------------------------------------- /Image-Processing/Cartoonify Image/images/sunset.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Cartoonify Image/images/sunset.jpg -------------------------------------------------------------------------------- /Image-Processing/Color_Detection/Readme.md: -------------------------------------------------------------------------------- 1 | # Color Detection 2 | 3 | This is a python script which we can use to determine the color of a part of image. 4 | 5 | ## Installation 6 | 7 | * Use the package manager [pip](https://pip.pypa.io/en/stable/) to install Opencv. 8 | 9 | ```bash 10 | pip install opencv-python 11 | ``` 12 | * Install Numpy 13 | 14 | ```bash 15 | pip install numpy 16 | ``` 17 | * Install Pandas 18 | 19 | ```bash 20 | pip install pandas 21 | ``` 22 | 23 | ## How it works 24 | 25 | * When the user double clicks on the image, then color of that part of image is shown in a box. 26 | 27 | ## How to run in CMD 28 | 29 | > python color_detection.py -i 30 | 31 | ## Screenshot 32 | 33 | ![](../Color_Detection/color_sample.png) -------------------------------------------------------------------------------- /Image-Processing/Color_Detection/color_sample.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Color_Detection/color_sample.png -------------------------------------------------------------------------------- /Image-Processing/Detecting Contours/Readme.md: -------------------------------------------------------------------------------- 1 | [![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com) 2 | ## Detecting Geometrical shapes in an image using OpenCV 3 | ### What is Contours? 4 | 5 | Contours can be explained simply as a curve joining all the continuous points (along the boundary), having the same color or intensity. 6 | The contours are a useful tool for shape analysis and object detection and recognition. 7 | 8 | ### Why we discussing about contours? 9 | We will be using Contours to first find the curving of object, then will be checkin and naming about shape of it depending on sides of object. 10 | 11 | ## Approach : 12 | The approach we would use to detect the shape of a given polygon will be based on classifying the detected shape on the basis of a number of sides it has. 13 | For example, if the detected polynomial has 3 sides, then it could be considered as a triangle, if the polynomial has 4 sides then it could be classified as a square or a rectangle, and so on. 14 | 15 | ### Important : 16 | Please add the image you want to use this on in the same folder you are saving the code, or else add the whole location. 17 | 18 | ## Language used : Python 19 | 20 | 21 | ## Libraries used: 22 | 1. OpenCV 23 | 2. Numpy 24 | 25 | 26 | ### Input 27 | 28 |
29 | 30 |
31 | 32 | 33 | ### output 34 | 35 |
36 | 37 |
38 | 39 | -------------------------------------------------------------------------------- /Image-Processing/Detecting Contours/detecting_geometrical_shapes.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | 4 | img = cv2.imread('shapes.PNG') 5 | imgGry = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 6 | 7 | ret , thrash = cv2.threshold(imgGry, 240 , 255, cv2.CHAIN_APPROX_NONE) 8 | contours , hierarchy = cv2.findContours(thrash, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) 9 | 10 | for contour in contours: 11 | approx = cv2.approxPolyDP(contour, 0.01* cv2.arcLength(contour, True), True) 12 | cv2.drawContours(img, [approx], 0, (0, 0, 0), 5) 13 | x = approx.ravel()[0] 14 | y = approx.ravel()[1] - 5 15 | 16 | if len(approx) == 3: 17 | cv2.putText( img, "Triangle", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0) ) 18 | elif len(approx) == 4 : 19 | x, y , w, h = cv2.boundingRect(approx) 20 | aspectRatio = float(w)/h 21 | print(aspectRatio) 22 | 23 | if aspectRatio >= 0.95 and aspectRatio < 1.05: 24 | cv2.putText(img, "square", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0)) 25 | 26 | else: 27 | cv2.putText(img, "rectangle", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0)) 28 | 29 | elif len(approx) == 5 : 30 | cv2.putText(img, "pentagon", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0)) 31 | 32 | elif len(approx) == 10 : 33 | cv2.putText(img, "star", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0)) 34 | 35 | else: 36 | cv2.putText(img, "circle", (x, y), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 0)) 37 | 38 | cv2.imshow('shapes', img) 39 | cv2.waitKey(0) 40 | cv2.destroyAllWindows() 41 | -------------------------------------------------------------------------------- /Image-Processing/Detecting Contours/output2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Detecting Contours/output2.JPG -------------------------------------------------------------------------------- /Image-Processing/Detecting Contours/shapes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Detecting Contours/shapes.png -------------------------------------------------------------------------------- /Image-Processing/Face_detection/Face_detection.py: -------------------------------------------------------------------------------- 1 | import cv2 ##Import OpenCv 2 | 3 | face = cv2.CascadeClassifier('C:/Users/91976/Desktop/haarcascade_frontalface_default.xml') ##'haarcascade_frontalface_default.xml' an opencv classifier for face detection 4 | cap = cv2.VideoCapture(0) ##capturevideo by webcam or your laptop default cam for webcame => 1 and for defalut laptop camera => 2 5 | 6 | while True: 7 | sucess , img = cap.read() 8 | gray = cv2.cvtColor( img , cv2.COLOR_BGR2GRAY ) ##before detecting face you should convert img or video into gray image 9 | faces = face.detectMultiScale( gray ,1.1 ,5 ) 10 | 11 | for ( x , y , w , h) in faces: 12 | cv2.rectangle(img,( x , y ),( x*w , y*h ),(255,0,0),2) ##will create the rectangle where face is detected 13 | 14 | cv2.imshow('img',img) 15 | k = cv2.waitKey(30) & 0xff 16 | if k == 27: 17 | break 18 | 19 | cap.release() 20 | -------------------------------------------------------------------------------- /Image-Processing/Face_detection/README.md: -------------------------------------------------------------------------------- 1 | # Image Processing 2 | 3 | Image Processing is most commonly termed as 'Digital Image Processing' and the domain in which it is frequently used is 'Computer Vision'. 4 | Don't be confused - we are going to talk about both of these terms and how they connect. 5 | Both Image Processing algorithms and Computer Vision (CV) algorithms take an image as input; however, in image processing, 6 | the output is also an image, whereas in computer vision the output can be some features/information about the image. 7 | 8 | ## OpenCV 9 | 10 | ![](https://logodix.com/logo/1989939.png) 11 | 12 | ## Installation 13 | 14 | ### Windows 15 | 16 | $ pip install opencv-python 17 | ### MacOS 18 | $ brew install opencv3 --with-contrib --with-python3 19 | ### Linux 20 | $ sudo apt-get install libopencv-dev python-opencv 21 | -------------------------------------------------------------------------------- /Image-Processing/HANDWRITING RECOGNIZER/hand.py: -------------------------------------------------------------------------------- 1 | 2 | # Baseline MLP for MNIST dataset 3 | from keras.datasets import mnist 4 | from keras.models import Sequential 5 | from keras.layers import Dense 6 | from keras.utils import np_utils 7 | # load data 8 | (X_train, y_train), (X_test, y_test) = mnist.load_data() 9 | # flatten 28*28 images to a 784 vector for each image 10 | num_pixels = X_train.shape[1] * X_train.shape[2] 11 | X_train = X_train.reshape((X_train.shape[0], num_pixels)).astype('float32') 12 | X_test = X_test.reshape((X_test.shape[0], num_pixels)).astype('float32') 13 | # normalize inputs from 0-255 to 0-1 14 | X_train = X_train / 255 15 | X_test = X_test / 255 16 | # one hot encode outputs 17 | y_train = np_utils.to_categorical(y_train) 18 | y_test = np_utils.to_categorical(y_test) 19 | num_classes = y_test.shape[1] 20 | # define baseline model 21 | def baseline_model(): 22 | # create model 23 | model = Sequential() 24 | model.add(Dense(num_pixels, input_dim=num_pixels, kernel_initializer='normal', activation='relu')) 25 | model.add(Dense(num_classes, kernel_initializer='normal', activation='softmax')) 26 | # Compile model 27 | model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) 28 | return model 29 | # build the model 30 | model = baseline_model() 31 | # Fit the model 32 | model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200, verbose=2) 33 | # Final evaluation of the model 34 | scores = model.evaluate(X_test, y_test, verbose=0) 35 | print("Baseline Error: %.2f%%" % (100-scores[1]*100)) 36 | -------------------------------------------------------------------------------- /Image-Processing/HANDWRITING RECOGNIZER/readme.md: -------------------------------------------------------------------------------- 1 | ## PYTHON HANDWRITING RECOGNIZER 2 | 3 | **1.**The first hidden layer is a convolutional layer called a Convolution2D. The layer has 32 feature maps, which with the size of 5×5 and a rectifier activation function. 4 | **2**This is the input layer, expecting images with the structure outline above [pixels][width][height]. 5 | **3.**Next we define a pooling layer that takes the max called MaxPooling2D. It is configured with a pool size of 2×2. 6 | **4.**The next layer is a regularization layer using dropout called Dropout. It is configured to randomly exclude 20% of neurons in the layer in order to reduce overfitting. 7 | **5.**Next is a layer that converts the 2D matrix data to a vector called Flatten. It allows the output to be processed by standard fully connected layers. 8 | **6.**Next a fully connected layer with 128 neurons and rectifier activation function. 9 | **7.**Finally, the output layer has 10 neurons for the 10 classes and a softmax activation function to output probability-like predictions for each class. 10 | 11 | #RUNNING THE CODE 12 | run the code with the following command 13 | 14 | ``` 15 | python hand.py 16 | ``` -------------------------------------------------------------------------------- /Image-Processing/Hough_Transform/HoughTransform_without_opencv.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | import cv2 4 | image=cv2.imread('image.jfif') 5 | img=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 6 | edges = cv2.Canny(img,100,200) 7 | 8 | def hough_line(edges): 9 | theta= np.arange(0,180,1) ## Theta 0 - 180 degree 10 | cos = np.cos(np.deg2rad(theta)) 11 | sin = np.sin(np.deg2rad(theta)) 12 | 13 | # Generate a accumulator matrix to store the values 14 | rho_range = int(np.hypot(edges.shape[0] , edges.shape[1])) #max value of rho size =2*diagonal_length 15 | accumulator = np.zeros((2 * rho_range, len(theta)), dtype=np.uint8) 16 | 17 | # Threshold to get edges pixel location (x,y) 18 | edge_pixels = np.where(edges == 255) #returns b bool matrix (True if edge_point=255; False is edge_point!=255) 19 | coordinates = list(zip(edge_pixels[0], edge_pixels[1])) #to access the edge points 20 | 21 | # Calculate rho value for each edge location (x,y) with all the theta range 22 | for p in range(len(coordinates)): 23 | for t in range(len(theta)): 24 | rho = int(round(coordinates[p][1] * cos[t] + coordinates[p][0] * sin[t])) #compute rho=x*cost+y*sint 25 | accumulator[rho, t] += 1 #increment the accumulator cell 26 | return accumulator 27 | 28 | accumulator=hough_line(edges) 29 | 30 | # Function to do hough line transform\ 31 | 32 | #print(len(accumulator>=90) 33 | # Threshold some high values then draw the line 34 | edge_pixels = np.where(accumulator > 75) 35 | 36 | coordinates = list(zip(edge_pixels[0], edge_pixels[1])) 37 | 38 | # Use line equation to draw detected line on an original image 39 | for i in range(0, len(coordinates)): 40 | a = np.cos(np.deg2rad(coordinates[i][1])) 41 | b = np.sin(np.deg2rad(coordinates[i][1])) 42 | x0 = a*coordinates[i][0] 43 | y0 = b*coordinates[i][0] 44 | 45 | x1 = int(x0 + 255*(-b)) #here 255(any constant) is multiplied to strech the lines over the edges 46 | y1 = int(y0 + 255*(a)) 47 | x2 = int(x0 - 255*(-b)) 48 | y2 = int(y0 - 255*(a)) 49 | 50 | 51 | cv2.line(image,(x1,y1),(x2,y2),(0,255,0),1) 52 | 53 | cv2.imwrite('Linedetection_without_opencv.png',image) 54 | -------------------------------------------------------------------------------- /Image-Processing/Hough_Transform/hough_Transform.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | img = cv2.imread("image.jfif") 4 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 5 | edges = cv2.Canny(gray, 75, 150) 6 | lines = cv2.HoughLinesP(edges, 1, np.pi/180, 30, maxLineGap=250) 7 | for line in lines: 8 | x1, y1, x2, y2 = line[0] 9 | cv2.line(img, (x1, y1), (x2, y2), (0, 0, 128), 1) 10 | cv2.imwrite('lines__detected.png',img) 11 | -------------------------------------------------------------------------------- /Image-Processing/Hough_Transform/image.jfif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Hough_Transform/image.jfif -------------------------------------------------------------------------------- /Image-Processing/Hough_Transform/readme.md: -------------------------------------------------------------------------------- 1 | HOUGH TRANSFORM 2 | 3 | Hough transform can be used to detect lines, circles or other parametric curves. The goal is to find the location of lines in images. Hough transform can detect lines, circles and other structures if their parametric equation is known. It can give robust detection under noise and partial occlusion It can give robust detection under noise and partial occlusion. 4 | 5 | Algorithm 6 | 7 | 1. Perform Edge detection on the original image by suitable edge detection technique. 8 | 2. Decide on the range of ρ and θ. Often, the range of θ is [ 0, 180 ] degrees and ρ is [ -d,d ] where d is the length of the edge image’s diagonal. 9 | 3. Create a 2D array called the accumulator representing the Hough Space with dimension (num_rhos, num_thetas) and initialize all its values to zero. 10 | 4. For every pixel on the edge image, check whether the pixel is an edge pixel. If it is an edge pixel, loop through all possible values of θ, calculate the corresponding ρ, find the θ and ρ index in the accumulator, and increment the accumulator base on those index pairs. 11 | 5. Loop through all the values in the accumulator. If the value is larger than a certain threshold, get the ρ and θ index, get the value of ρ and θ from the index pair which can then be converted back to the form of y=ax+b. 12 | 13 | 14 | INPUT IMAGE: 15 | 16 | ![image](https://user-images.githubusercontent.com/46890827/94119467-9486b280-fe6c-11ea-9a52-e0bc50e14df2.png) 17 | 18 | OUTPUT IMAGE: 19 | 20 | ![image](https://user-images.githubusercontent.com/46890827/94119579-bc761600-fe6c-11ea-8309-f606768b1c87.png) 21 | 22 | -------------------------------------------------------------------------------- /Image-Processing/Image To Sepia Effect/README.md: -------------------------------------------------------------------------------- 1 | # Image to Sepia image 2 | The original image is converted into Sepia filtered image. 3 | 4 | ### Results: 5 | 6 | #### Original Image 7 | Original_image 8 | 9 | #### Sepia Image 10 | Sepia_image 11 | -------------------------------------------------------------------------------- /Image-Processing/Image To Sepia Effect/Taj_Mahal.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Image To Sepia Effect/Taj_Mahal.jpg -------------------------------------------------------------------------------- /Image-Processing/Image To Sepia Effect/original.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Image To Sepia Effect/original.jpg -------------------------------------------------------------------------------- /Image-Processing/Image To Sepia Effect/sepia image convertor.py: -------------------------------------------------------------------------------- 1 | # Importing libraries 2 | import cv2 3 | import numpy as np 4 | 5 | img = cv2.imread('taj_mahal.jpg') 6 | original = img.copy() 7 | # Converting into float 8 | img = np.array(img, dtype=np.float64) 9 | # Multipying image with special sepia matrix 10 | img = cv2.transform(img, np.matrix([[0.272, 0.534, 0.131], 11 | [0.349, 0.686, 0.168], 12 | [0.393, 0.769, 0.189]])) 13 | img[np.where(img > 255)] = 255 14 | # Converting into integer again 15 | img = np.array(img, dtype=np.uint8) 16 | cv2.imshow("original", original) 17 | cv2.imshow("sepia", img) 18 | cv2.waitKey(0) 19 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /Image-Processing/Image To Sepia Effect/sepia.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Image To Sepia Effect/sepia.jpg -------------------------------------------------------------------------------- /Image-Processing/ImageCropper/Data/CropDEMO.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/ImageCropper/Data/CropDEMO.gif -------------------------------------------------------------------------------- /Image-Processing/ImageCropper/Data/Man_United.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/ImageCropper/Data/Man_United.jpeg -------------------------------------------------------------------------------- /Image-Processing/ImageCropper/Data/cropped image1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/ImageCropper/Data/cropped image1.png -------------------------------------------------------------------------------- /Image-Processing/ImageCropper/README.md: -------------------------------------------------------------------------------- 1 | # Image Cropper 2 | This code allows you to crop images and save them. 3 | 4 | ### Executing the code 5 | 1. Run the .py file by running the command ``` python3 crop.py``` in the terminal or cmd. 6 | 2. Use the **Left** mouse button to drag out a rectangular region of the image you want to crop. **Release** the button, once you are done. 7 | 3. The selected rectangular is shown on the image. 8 | 4. Press **c** to crop the image. A new window opens up. 9 | a) Press **s** to save the cropped image. 10 | b) Press **r** to reset and return to the original image. 11 | 5. Repeat from step 2 to crop more images. 12 | 13 | ### Demo 14 | ![](https://github.com/Pranjalmishra30/Awesome-Python-Scripts/blob/PranjalMishra/Image-Processing/ImageCropper/Data/CropDEMO.gif) 15 | 16 | ### Refrences 17 | 1. Mouse events [tutorial](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_mouse_handling/py_mouse_handling.html) 18 | 2. Pyimagesearch [tutorial](https://www.pyimagesearch.com/2015/03/09/capturing-mouse-click-events-with-python-and-opencv/) 19 | -------------------------------------------------------------------------------- /Image-Processing/ImageCropper/crop.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | refpt = [] #List of refrence points 3 | 4 | def select_roi (event,x,y,flags,param): 5 | global refpt #Global refrences 6 | 7 | if event == cv2.EVENT_LBUTTONDOWN: # When the left mouse button is cliked 8 | refpt = [(x , y)] 9 | 10 | elif event == cv2.EVENT_LBUTTONUP: # When the left mouse button is released 11 | refpt.append((x , y)) # recording the last coordinates 12 | cv2.rectangle(img_main,refpt[0],refpt[1],(0,255,0),2) 13 | cv2.imshow("frame",img_main) 14 | print("Selection Successful") 15 | 16 | img = cv2.imread("Data/Man_United.jpeg") 17 | img_main = cv2.resize(img,(400,400)) #Resizing image 18 | 19 | clone = img_main.copy() # To reset the image after cropping 20 | clone2 = img_main.copy() # To crop a section out without affecting the original image 21 | 22 | cv2.namedWindow("frame") 23 | cv2.setMouseCallback("frame",select_roi) 24 | 25 | i = 1 # Numbering for saving images 26 | 27 | while True: 28 | cv2.imshow("frame",img_main) 29 | var = cv2.waitKey(0) 30 | 31 | # Select a region , then press c to crop that portion 32 | 33 | if var == ord('c'): # Crop selected images 34 | 35 | if len(refpt) == 2: 36 | roi = clone2[ refpt[0][1] : refpt[1][1] , refpt[0][0] : refpt[1][0] ] # [x1:x2 , y1:y2] 37 | cv2.namedWindow("Crop") 38 | cv2.imshow("Crop",roi) 39 | print("Cropped") 40 | 41 | var2 = cv2.waitKey(0) 42 | 43 | if var2 == ord('s'): # Saving cropped image 44 | cv2.imwrite("Data/cropped image{}.png".format(i),roi) 45 | i = i+1 46 | print("image saved\n") 47 | cv2.destroyWindow("Crop") 48 | img_main = clone.copy() 49 | 50 | elif var2 == ord('r'): # Reset 51 | cv2.destroyWindow("Crop") 52 | print("Reset\n") 53 | img_main = clone.copy() 54 | 55 | elif var == ord('q'): # Exit the loop 56 | print("Exiting ...") 57 | break 58 | 59 | cv2.destroyAllWindows() 60 | -------------------------------------------------------------------------------- /Image-Processing/Image_Crop_(resize)/Image_crop.py: -------------------------------------------------------------------------------- 1 | import cv2 ##import the module 2 | img = cv2.imread("rose.jpg") ##read your image 3 | y = 0 ##HEIGHT from 4 | x = 0 ##WIDTH from 5 | h = 300 ##HEIGHT 6 | w = 510 ##WIDTH 7 | crop_image = img[x:w, y:h] 8 | cv2.imshow("Cropped", crop_image) ##display Cropped image 9 | cv2.waitKey(0) 10 | -------------------------------------------------------------------------------- /Image-Processing/Image_Crop_(resize)/README.md: -------------------------------------------------------------------------------- 1 | # Image Processing 2 | 3 | Image Processing is most commonly termed as 'Digital Image Processing' and the domain in which it is frequently used is 'Computer Vision'. 4 | Don't be confused - we are going to talk about both of these terms and how they connect. 5 | Both Image Processing algorithms and Computer Vision (CV) algorithms take an image as input; however, in image processing, 6 | the output is also an image, whereas in computer vision the output can be some features/information about the image. 7 | 8 | ## OpenCV 9 | 10 | ![](https://logodix.com/logo/1989939.png) 11 | 12 | ## Installation 13 | 14 | ### Windows 15 | 16 | $ pip install opencv-python 17 | ### MacOS 18 | $ brew install opencv3 --with-contrib --with-python3 19 | ### Linux 20 | $ sudo apt-get install libopencv-dev python-opencv -------------------------------------------------------------------------------- /Image-Processing/Image_Crop_(resize)/rose.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Image_Crop_(resize)/rose.jpg -------------------------------------------------------------------------------- /Image-Processing/Image_filters_using_convolution/README.md: -------------------------------------------------------------------------------- 1 | 2 | ## Image filters using convolution ## 3 | 4 | - Convolution is a technique widely used in image processing . Convolution is a mathematical operation on two functions that produces a third function expressing how the shape of one is modified by the other. (As defined in Wikipedia). 5 | 6 | - Though this technique is widely used in image processing, in my implementation it can be used as an image filter. 7 | 8 | - Images are made of pixels, colored images have 3 streams (red, green, blue), these can be visualised as a matrix which is 3 dimensional 9 | - Each of the red, blue and green are streams, stacked together to form a cube 10 | 11 | - A kernel or a smaller matrix, in this case a 3X3 matrix is used to perform convolution. 12 | 13 | - The kernel is used to perform dot product with the image. The resultant is an image which has different properties. 14 | 15 | - This script written in Python, implements convolution over colored images. 16 | 17 | - The end result is the application of filters to images. 18 | 19 | - I have used tensorflow, numpy and the image processing library. 20 | 21 | - The images attached show an image before and after blurring. 22 | 23 | ![Image](./images/before.png) 24 | 25 | - This is before applying convolution. 26 | 27 | ![Image](./images/after.png) 28 | 29 | - This is after applying convolution. 30 | 31 | -------------------------------------------------------------------------------- /Image-Processing/Image_filters_using_convolution/images/after.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Image_filters_using_convolution/images/after.png -------------------------------------------------------------------------------- /Image-Processing/Image_filters_using_convolution/images/before.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Image_filters_using_convolution/images/before.png -------------------------------------------------------------------------------- /Image-Processing/Invisible_cloak/README.md: -------------------------------------------------------------------------------- 1 | # Invisible Cloak 2 | This is a python script about the cloak of invisibility which was used by harry to become invisible. 3 | 4 | ## How it works 5 | * It captures and store the background. 6 | * Detect the defined color using color detection. 7 | * Segment out the red colored cloth by generating a mask. 8 | * Generate the final augmented output to create a magical effect. 9 | 10 | ## Installation 11 | * Use the package manager [pip](https://pip.pypa.io/en/stable/) to install Opencv. 12 | 13 | ```bash 14 | pip install opencv-python 15 | ``` 16 | * Install Numpy 17 | 18 | ```bash 19 | pip install numpy 20 | ``` -------------------------------------------------------------------------------- /Image-Processing/Invisible_cloak/cloak.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | import time 4 | 5 | print(""" 6 | BE PREPARE YOU WILL BE INVISIBLE SOON............ 7 | """) 8 | 9 | if __name__ == '__main__': 10 | cap = cv2.VideoCapture(0) 11 | 12 | #For capturing output video 13 | fourcc = cv2.VideoWriter_fourcc(*'XVID') 14 | out = cv2.VideoWriter('harry.avi' , fourcc, 20.0, (640,480)) 15 | time.sleep(2) 16 | background = 0 17 | 18 | #capturing background 19 | for i in range(30): 20 | ret, background = cap.read() 21 | 22 | #capturing image 23 | while(cap.isOpened()): 24 | ret, img = cap.read() 25 | 26 | if not ret: 27 | break 28 | #HSV stands for Hue Satrurated Value 29 | hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV) 30 | 31 | #YOU CAN CHANGE THE COLOR VALUE BELOW ACCORDING TO YOUR CLOTH COLOR 32 | lower_red = np.array([0,120,70]) 33 | upper_red = np.array([10,255,255]) 34 | mask1 = cv2.inRange(hsv , lower_red , upper_red) 35 | 36 | lower_red = np.array([170,120,70]) 37 | upper_red = np.array([180,255,255]) 38 | mask2 = cv2.inRange(hsv , lower_red , upper_red) 39 | 40 | mask1 = mask1 + mask2 41 | 42 | #Open and clean the mask image 43 | mask1=cv2.morphologyEx(mask1, cv2.MORPH_OPEN ,np.ones((3,3) , np.uint8) , iterations=2) 44 | 45 | mask2=cv2.morphologyEx(mask1, cv2.MORPH_DILATE ,np.ones((3,3) , np.uint8) , iterations=1) 46 | 47 | mask2 = cv2.bitwise_not(mask1) 48 | 49 | #Generating the final output 50 | res1 = cv2.bitwise_and(background, background, mask=mask1) 51 | res2 = cv2.bitwise_and(img, img, mask=mask2) 52 | 53 | final_output = cv2.addWeighted(res1 , 1, res2 , 1, 0) 54 | 55 | cv2.imshow('Invisibility Game' , final_output) 56 | k=cv2.waitKey(10) 57 | if k==27: 58 | print("Escape hit, closing...") 59 | break 60 | 61 | cap.release() 62 | out.release() 63 | cv2.destroyAllWindows() 64 | -------------------------------------------------------------------------------- /Image-Processing/JpgToPngConvertor/JpgToPngConvertor.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Script uses Pillow module to read the image and convert it to png. 3 | sys module for accepting inputs from terminal and os module 4 | for operations on pathnames. 5 | 6 | Install Pillow module through "pip install pillow" 7 | ''' 8 | 9 | import sys,os 10 | from PIL import Image 11 | 12 | source_folder = sys.argv[1] # Accepts source folder given in terminal 13 | destination_folder = sys.argv[2] # Accepts destination folder given in terminal 14 | 15 | if not os.path.exists(destination_folder): #Check if destination folder exists,if not creates one 16 | os.makedirs(destination_folder) 17 | 18 | for filename in os.listdir(source_folder): # For each file present in Source folder 19 | file = os.path.splitext(filename)[0] # Splits file name into as tuple as ('filename','.extension') 20 | img = Image.open(f'{source_folder}/{filename}') 21 | img.save(f'{destination_folder}/{file}.png','png') #Converts to png format 22 | print("Image converted!") 23 | 24 | ''' 25 | Sample input to run in terminal: 26 | ->Python3 JpgToPngConvertor.py Source_Images Destination_Images 27 | 28 | Output: 29 | Images in Source_Images folder will be converted into Png Images and gets stored in 30 | Destination_Images folder 31 | ''' 32 | 33 | -------------------------------------------------------------------------------- /Image-Processing/JpgToPngConvertor/README.md: -------------------------------------------------------------------------------- 1 | # JPG to PNG Convertor 2 | 3 | * This script converts the list of JPG images available in source folder to PNG images 4 | which will get stored in destination folder with help of Pillow module. 5 | 6 | * Pillow is a free and open-source additional library for the Python programming language 7 | that adds support for opening, manipulating, and saving many different image file formats. 8 | 9 | * Pillow module can be installed using following command "pip install pillow" 10 | -------------------------------------------------------------------------------- /Image-Processing/JpgToPngConvertor/Source_Images/bulbasaur.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/JpgToPngConvertor/Source_Images/bulbasaur.jpg -------------------------------------------------------------------------------- /Image-Processing/JpgToPngConvertor/Source_Images/charmander.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/JpgToPngConvertor/Source_Images/charmander.jpg -------------------------------------------------------------------------------- /Image-Processing/JpgToPngConvertor/Source_Images/pikachu.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/JpgToPngConvertor/Source_Images/pikachu.jpg -------------------------------------------------------------------------------- /Image-Processing/JpgToPngConvertor/Source_Images/squirtle.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/JpgToPngConvertor/Source_Images/squirtle.jpg -------------------------------------------------------------------------------- /Image-Processing/Qr_scanner/Qr_scanner.py: -------------------------------------------------------------------------------- 1 | import cv2 ##import the module opencv 2 | import numpy as np ##import the module numpy 3 | import pyzbar.pyzbar as pyzbar ##import the module pyzbar 4 | 5 | img = cv2.imread("qr.png") ##read your image 6 | decode_QR = pyzbar.decode(img) ##function to decode QR 7 | 8 | for i in decode_QR: 9 | print("your scanned QR :",i.data) 10 | 11 | cv2.imshow("QR ", img) ##display Cropped image 12 | cv2.waitKey(0) 13 | -------------------------------------------------------------------------------- /Image-Processing/Qr_scanner/README.md: -------------------------------------------------------------------------------- 1 | # Image Processing 2 | 3 | Image Processing is most commonly termed as 'Digital Image Processing' and the domain in which it is frequently used is 'Computer Vision'. 4 | Don't be confused - we are going to talk about both of these terms and how they connect. 5 | Both Image Processing algorithms and Computer Vision (CV) algorithms take an image as input; however, in image processing, 6 | the output is also an image, whereas in computer vision the output can be some features/information about the image. 7 | 8 | ## OpenCV 9 | 10 | ![](https://logodix.com/logo/1989939.png) 11 | 12 | ## Installation 13 | 14 | ### Windows 15 | $ pip install opencv-python 16 | $ pip install pyzbar 17 | ### MacOS 18 | $ brew install opencv3 --with-contrib --with-python3 19 | $ brew install zbar 20 | ### Linux 21 | $ sudo apt-get install libopencv-dev python-opencv 22 | $ sudo apt-get install libzbar0 23 | -------------------------------------------------------------------------------- /Image-Processing/Qr_scanner/qr.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Image-Processing/Qr_scanner/qr.png -------------------------------------------------------------------------------- /Image-Processing/README.md: -------------------------------------------------------------------------------- 1 | # Image-Processing 2 | Image processing has been used to create weird and beautiful modifications to pictures many of us have seen online. Older black and white photos can be brought to life using colorization techniques. On the other hand, color photos can be made to look like old black and white photos. In addition to distorting images for entertainment, image processing can be used for more serious applications, for example, to enhance medical imaging to screen patients for cancer or other diseases. 3 | -------------------------------------------------------------------------------- /Image-Processing/ocr-img-to-txt/ocr-img-to-txt.md: -------------------------------------------------------------------------------- 1 | # OCR [Optical Character Recognition] - Extact Text from Images 📝 2 | [![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com) 3 | 4 | ## Instructions 📑 5 | 6 | ### Step 1: 7 | Installing Tesseract 8 | 9 | You can either [Install Tesseract via pre-built binary package](https://tesseract-ocr.github.io/tessdoc/Home.html) 10 | or [build it from source](https://tesseract-ocr.github.io/tessdoc/Compiling.html). 11 | 12 | Supported Compilers are: 13 | 14 | * GCC 4.8 and above 15 | * Clang 3.4 and above 16 | * MSVC 2015, 2017, 2019 17 | 18 | Other compilers might work, but are not officially supported. 19 | 20 | ### Step 2: 21 | Provide the path to the Pytesseract. Here ⬇ 22 | ![Screenshot (143)](https://user-images.githubusercontent.com/55796944/90473189-ec305080-e13f-11ea-98a8-47b9dd1db499.jpg) 23 | 24 | ### Step 3: 25 | Provide the path to the Image you want to extract Text From. Here ⬇ 26 | ![Screenshot (144)](https://user-images.githubusercontent.com/55796944/90473402-75478780-e140-11ea-954c-990342dafa0e.jpg) 27 | 28 | #### Sit back and Relax.. Let the Script do the Job.. ☕ 29 | 30 | [![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com) 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /Image-Processing/ocr-img-to-txt/ocr-img-to-txt.py: -------------------------------------------------------------------------------- 1 | import pytesseract 2 | from PIL import Image 3 | 4 | # path to the Tessaract 5 | pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" 6 | 7 | def convert(): 8 | #Image to Convert 9 | img = Image.open(r"img1.jpg") 10 | #sending Image to Pytesseract 11 | text = pytesseract.image_to_string(img) 12 | # printing out Text from the Images\ 13 | print(text) 14 | # If you want to save the output in a file, if not comment out the next two lines 15 | # To open a file in write mode 16 | newfile = open("newfile.txt", "w+") 17 | # To Write the text in that file 18 | newfile.write(text) 19 | 20 | convert() 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Awesome-Python-Scripts 2 | [![forthebadge](https://forthebadge.com/images/badges/built-by-developers.svg)](https://forthebadge.com) 3 | [![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](https://forthebadge.com) 4 | [![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com) 5 | [![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com) 6 | 7 | 8 | ## 📌 Introduction 9 | A curated collection of awesome **Python** scripts from basic to advance with automation task scripts. This is the project from which you can learn that how to contribute a open source contest and specially during in Open source contest as a **Pythoneer**. 10 | 11 | ## 💥 How to Contribute? 12 | - All contributions welcomed. Follow these [guidelines](Contribution.md) to contribute. 13 | - Take a look at [guidelines](Contribution.md). 14 | 15 | > print("Start contributing for Automation-Python-Scripts") 16 | 17 | 18 | ## ❤️ Project Admin 19 | 20 | | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | 21 | | 22 | 23 | **[Ankit Dobhal](https://www.linkedin.com/in/ankit-dobhal-aa237015b/)** 24 | 25 | | | 26 | 27 | ## ⚡ Contributors 28 | - All Contributors can be found in the [contributor](https://github.com/ankitdobhal/Awesome-Python-Scripts/graphs/contributors) section. 29 | 30 | 31 | ## License 32 | This project follows GNU [License](LICENSE) 33 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Amazon-price-tracker/README.md: -------------------------------------------------------------------------------- 1 | ## Amazon Price Tracker ## 2 | - This script built in Python is an Amazon Price Tracker. 3 | - The user enters : 4 | - The URL of the product of which he would like the track the price of. 5 | - His/Her budget for the product. 6 | - His/Her Email credentials. 7 | - The script runs continuously and checks on the price of the product every 12 hours. 8 | - If the price of the product is equal to or below the user's budget, the user receives an email confirmation. 9 | - The price of the product is logged into a file named price_logger.txt every 12 hours. 10 | 11 | ## Working and Usage ## 12 | - The BeautifulSoup library is used to scrape the price of the product from the Amazon site. 13 | - On Amazon, the prices of products are either expressed as a range or as a single number. 14 | - If the budget is within the range, an email will be sent. 15 | - In the script, headers need to be used to make the get request to the Amazon site. 16 | - In place of headers, the user must replace it with the result of **my user agent** must be used instead (this can be looked up in Google). 17 | - The Email settings of the user must be configured to operate on less secure mode to facilitate the sending of emails. 18 | 19 | ![Image](../images/lesssecure.png) 20 | 21 | - After this, the script can be run. 22 | 23 | - Using this as an example 24 | 25 | ![Image](../images/single.png) 26 | 27 | - The user enters 700 rupees as the budget, as the price is lesser than the budget the following email is sent, else the program continues to run till the condition is satisfied. 28 | 29 | ![Image](../images/confirm.png) 30 | 31 | - The prices are also logged into the file price_logger.txt as shown, so the user will have an account of the changes the price underwent. 32 | 33 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Amazon-price-tracker/images/confirm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Amazon-price-tracker/images/confirm.png -------------------------------------------------------------------------------- /System-Automation-Scripts/Amazon-price-tracker/images/lesssecure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Amazon-price-tracker/images/lesssecure.png -------------------------------------------------------------------------------- /System-Automation-Scripts/Amazon-price-tracker/images/single.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Amazon-price-tracker/images/single.png -------------------------------------------------------------------------------- /System-Automation-Scripts/Amazon-price-tracker/mail_in_python.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import smtplib 4 | 5 | #The smtp module (Simple Mail Transfer Protocol) enables sending emails in python 6 | #The sender's email must be configured to less secure apps. 7 | #This configuration can be made on visiting account information. 8 | #Under the category security, less secure apps must turned on 9 | 10 | def send_confirmation(sender_email, receiver_email, password, price_range): 11 | 12 | #Subject of the Email 13 | subject = "Amazon product price " 14 | 15 | if len(price_range) == 1: 16 | cost = "The cost of the product is" + str(price_range[0]) 17 | else: 18 | cost = "The cost of the product is within the range " + str(price_range[0]) + " and " + str(price_range[1]) 19 | 20 | #Content of the email 21 | body_of_the_email = "Hello, This is to inform you that the price of the product you were looking for on Amazon is well-within your budget." + cost + " You can buy it right away." 22 | 23 | content = "Subject: {}\n\n{}".format(subject, body_of_the_email) 24 | 25 | #Specifications of the Email 26 | 27 | server = smtplib.SMTP("smtp.gmail.com" , 587) 28 | 29 | #Here the Gmail service is used, a different Email service can also be used 30 | #The port 587, across which the email is sent 31 | 32 | server.starttls() 33 | server.login(sender_email, password) 34 | 35 | #Login is authorised 36 | server.sendmail(sender_email, receiver_email, content) 37 | 38 | #Email is sent, prints success on sending the email 39 | 40 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Amazon-price-tracker/price_logger.txt: -------------------------------------------------------------------------------- 1 | The cost of the product is 649.0 at 2020-08-11 19:23:36.359383 2 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Automate-Telegram/README.md: -------------------------------------------------------------------------------- 1 | ## Automate Telegram 2 | - This script can be used to automate the process of sending messages in Telegram 3 | - Here the process of automation is achieved by using the framework Selenium. 4 | - Selenium is a portable framework for testing and automating web applications web applications 5 | 6 | ## Working 7 | 8 | ![Image](login.png) 9 | 10 | - The user is prompted to login and verify the phone number 11 | 12 | - The user will receive a code which has to be entered 13 | 14 | ![Image](code.png) 15 | 16 | - After the verification process, the user can send messages to the contacts 17 | 18 | ![Image](send.png) 19 | 20 | - The user can send multiple messages to the same user 21 | 22 | - The user can also send messages to multiple users 23 | 24 | ![Image](working.PNG) 25 | 26 | - An message sent from the commandline 27 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Automate-Telegram/automate_telegram.py: -------------------------------------------------------------------------------- 1 | #Imports and dependencies 2 | from selenium import webdriver 3 | import time 4 | from selenium.webdriver.common.keys import Keys 5 | 6 | time_wait_sixty = 60 7 | time_wait_four = 4 8 | 9 | #Here the process of automation is achieved by using the framework Selenium. 10 | #Selenium is a portable framework for testing and automating web applications web applications 11 | 12 | def automate_telegram(): 13 | #Path to the chromedriver must be entered without quotations 14 | PATH = input("Enter path to the location chromedriver ") 15 | chrome_path = PATH 16 | #Initiating and setting up the driver 17 | driver = webdriver.Chrome(chrome_path) 18 | #For logging into web telegram, the user must verify the phone number 19 | URL = "https://web.telegram.org/#/login" 20 | driver.get(URL) 21 | time.sleep(time_wait_sixty) 22 | user = 1 23 | while user: 24 | driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div[1]/div[1]/div/input").click() 25 | name = input("Enter the name of the person ") 26 | driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div[1]/div[1]/div/input").send_keys(name) 27 | time.sleep(time_wait_four) 28 | driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div[1]/div[2]/div/div[1]/ul/li").click() 29 | msg = 1 30 | while msg: 31 | message = input("Enter message ") 32 | driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div[2]/div[3]/div/div[3]/div[2]/div/div/div/form/div[2]/div[5]").send_keys(message) 33 | driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div[2]/div[3]/div/div[3]/div[2]/div/div/div/form/div[2]/div[5]").send_keys(Keys.ENTER) 34 | print("Do you want to send another message? ") 35 | msg = int(input("Enter 1 to continue, 0 to stop ")) 36 | if msg == 0: 37 | break 38 | 39 | print("Do you want to send messages to another contact? ") 40 | user = int(input("Enter 1 to continue, 0 to stop ")) 41 | 42 | return("All messages sent") 43 | 44 | if __name__ == "__main__": 45 | automate_telegram() 46 | 47 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Automate-Telegram/code.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Automate-Telegram/code.png -------------------------------------------------------------------------------- /System-Automation-Scripts/Automate-Telegram/login.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Automate-Telegram/login.png -------------------------------------------------------------------------------- /System-Automation-Scripts/Automate-Telegram/send.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Automate-Telegram/send.png -------------------------------------------------------------------------------- /System-Automation-Scripts/Automate-Telegram/working.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Automate-Telegram/working.PNG -------------------------------------------------------------------------------- /System-Automation-Scripts/Automatic attending meet/Readme.md: -------------------------------------------------------------------------------- 1 | 2 | # Online_Class_buddy 3 | This buddy will help you to attain online classes in your absence and will record the class for you. So as to review/revise when required. 4 | 5 | ## Quick links to the driver: 6 | 7 | 8 | 9 | ### How to use? 10 | 11 | Download the chrome driver from the above link. 12 |

Enter the path where the driver is saved in the code

13 |

Enter your mail id and password

14 |

& you are ready to go

15 | 16 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Email_Client/README.md: -------------------------------------------------------------------------------- 1 | # Email Client using Python for automating email shooting process 2 | Python email client that can be used to automate email sending process. 3 | 4 | ## Pre-requisites :rotating_light: 5 | [![GitHub top language](https://img.shields.io/github/languages/top/vinitshahdeo/PortScanner?logo=python&logoColor=white)](https://www.python.org/) 6 | - **Python** `>= v3.7.x` 7 | - Install Python from [here](https://www.python.org/). 8 | - **Pip** `>= v20.0.x` 9 | - Install pip from [here](https://pip.pypa.io/en/stable/installing/). 10 | 11 | ## How to run? :rocket: 12 | ### To run Email Client: (Via Terminal) 13 | - Update `email_client.py` file to enter Email credentials for the sender account as well as the recipient's address. 14 | - **Open terminal** and type **`python Email_CLient/email_client.py`**. 15 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Email_Client/password.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Email_Client/test.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Email_Client/test.txt -------------------------------------------------------------------------------- /System-Automation-Scripts/FolderSorter.py: -------------------------------------------------------------------------------- 1 | import os 2 | import shutil 3 | # None Movable extentions 4 | n_ext=['INI','DDL','SYS','REG'] 5 | # array of files ONLY no Folders included 6 | # added the u to support moving None-english file names 7 | files = [f for f in os.listdir(u'.') if os.path.isfile(f)] 8 | # parsing all files in the directory 9 | for filename in files: 10 | #extracting the extension and the name of the file 11 | file,extension = os.path.splitext(filename) 12 | #getting rid of . in the beggining of string 13 | extension = extension[1:] 14 | # trying not to move the script and the system files to folders 15 | if (not(filename=="code.py") and not(extension.upper() in n_ext)): 16 | #checking if the Folder made with extension exist and creating it if it doesnt exist 17 | if (not(os.path.isdir(os.getcwd()+'\\'+extension.upper()))): 18 | os.makedirs(os.getcwd()+'\\'+extension.upper()) 19 | # moving the file 20 | shutil.move(os.getcwd()+'\\'+filename,os.getcwd()+'\\'+extension.upper()+'\\'+filename) 21 | 22 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Google/Automating_Google.py: -------------------------------------------------------------------------------- 1 | # In this script we will automate Google using Selenium 2 | 3 | # Imports : 4 | from selenium import webdriver 5 | from selenium.webdriver.common.keys import Keys 6 | import time 7 | from time import sleep 8 | from webdriver_manager.chrome import ChromeDriverManager 9 | 10 | driver = webdriver.Chrome(ChromeDriverManager().install()) 11 | 12 | # enter the link of the google 13 | driver.get("https://www.google.com") 14 | 15 | # AUTOMATING CLICKING OF THE LINK TEXT 16 | 17 | # enter the name of the text 18 | element = driver.find_element_by_link_text("About") 19 | 20 | # delaying by 2 sec 21 | time.sleep(2) 22 | # clicking of the element is done by the below click method 23 | element.click() 24 | time.sleep(5) 25 | 26 | # AUTOMATING CLICKING OF BACKWARD AND FOORWARD BUTTON 27 | 28 | # going backward 29 | driver.back() 30 | 31 | time.sleep(5) 32 | 33 | # going forward 34 | driver.forward() 35 | 36 | # AUTOMATING THE REFRESH OF THE WEBPAGE 37 | time.sleep(10) 38 | driver.refresh() 39 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Google/Automating_Google_Search.py: -------------------------------------------------------------------------------- 1 | # In this script we will automate Google Search using Selenium 2 | 3 | # Imports : 4 | from selenium import webdriver 5 | from selenium.webdriver.common.keys import Keys 6 | import time 7 | from time import sleep 8 | from webdriver_manager.chrome import ChromeDriverManager 9 | 10 | 11 | driver = webdriver.Chrome(ChromeDriverManager().install()) 12 | 13 | # providing the link 14 | driver.get("https://www.google.com") 15 | 16 | # then we will look for the search bar name(here name is referred to the html code) 17 | element = driver.find_element_by_name("q") 18 | 19 | # this is to provide some delay so that we can easily see the process 20 | time.sleep(2) 21 | element.clear() 22 | 23 | # here whatever we have to search we can write between the parenthesis 24 | element.send_keys("Python") 25 | 26 | # for the enter button 27 | element.send_keys(Keys.RETURN) 28 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Google/README.md: -------------------------------------------------------------------------------- 1 | # System-Automation-Scripts 2 | ## Automating Google using Selenium 3 | 4 | #### Install Requirements : 5 | 1. Install Selenium by writing the following pip command, at command prompt - 6 | > pip install selenium 7 | 8 | 2. Install ChromeDriver 9 | 10 | #### Automating_Google_Search.py 11 | - This file contains the script to automate the Google Search , you just have to enter whatever you want to search & run the file. 12 | 13 | #### Automating_Google.py 14 | - This file contains the script to automate various tasks on Google like clicking the text link, cliking the forward and the backward button and refreshing of the page . -------------------------------------------------------------------------------- /System-Automation-Scripts/PDF_Tables_To_CSV/.gitignore: -------------------------------------------------------------------------------- 1 | # Vscode files 2 | .vscode 3 | 4 | # Sample Files 5 | sample.pdf 6 | sample2.pdf 7 | 8 | # Python 9 | __pycache__ -------------------------------------------------------------------------------- /System-Automation-Scripts/PDF_Tables_To_CSV/README.md: -------------------------------------------------------------------------------- 1 | # PDF to CSV 2 | This script will convert the tables in the PDF file into CSV files. Each CSV file has one table from the PDF and the number of CSV equal to the number of tables in the PDF. 3 | 4 | # Requirements 5 | `pip install tabula-py, pandas` 6 | 7 | # How to use? 8 | Just use the following command while executing the scrpit: 9 | 10 | `python app.py location_of_pdf pages` 11 | 12 | Pages have two options: 13 | - 'all' will extract tables from whole PDF 14 | - specific page (ex 1,2,54..) will extract table from that page 15 | 16 | Example: 17 | - `python app.py sample.pdf all` 18 | - `python app.py sample2.pdf 45` 19 | 20 | # Preview 21 | 22 | ![](preview.gif) 23 | -------------------------------------------------------------------------------- /System-Automation-Scripts/PDF_Tables_To_CSV/app.py: -------------------------------------------------------------------------------- 1 | import tabula 2 | import pandas as pd 3 | import sys 4 | 5 | def extract(path, number_pages): 6 | tables = tabula.read_pdf(path, multiple_tables=True, pages=number_pages) 7 | count = 1 8 | if len(tables)!=0: 9 | for table in tables: 10 | print 11 | print(f"Saving file -{count}") 12 | table.to_csv(f'Table- {count}.csv') 13 | count += 1 14 | print("All tables saved as seperate files !") 15 | else: 16 | print("No tables found !") 17 | 18 | if __name__ == "__main__": 19 | extract(sys.argv[1], sys.argv[2]) -------------------------------------------------------------------------------- /System-Automation-Scripts/PDF_Tables_To_CSV/preview.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/PDF_Tables_To_CSV/preview.gif -------------------------------------------------------------------------------- /System-Automation-Scripts/PingScanner.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # Automation with scapy 3 | import sys 4 | from scapy.all import * 5 | ip = sys.argv[1] # command line argument 6 | icmp = IP(dst=ip)/ICMP() 7 | #icmp = IP(dst=ip)/TCP() 8 | #IP defines the protocol for IP addresses 9 | #dst is the destination IP address 10 | #TCP defines the protocol for the ports 11 | resp = sr1(icmp,timeout=10) 12 | if resp == None: 13 | print("This host is down") 14 | else: 15 | print("This host is up") 16 | 17 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Questions_from_Project_Euler/README.md: -------------------------------------------------------------------------------- 1 | # Project Euler # 2 | 3 | ![Image](./images/euler_home.PNG) 4 | 5 | Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve 6 | 7 | This script written in Python, gets all the 700+ questions across 15 pages which is written into a CSV file named Project_Euler.csv 8 | 9 | Beautiful Soup is used for scraping the URL : https://projecteuler.net/archives 10 | 11 | Regular expressions have also been used in order to obtain the description of the questions 12 | 13 | ## Implementation ## 14 | 15 | Using **inspect element**, the contents of the page can be understood 16 | 17 | The structure of each page is as shown 18 | 19 | ![Image](./images/euler_questions.PNG) 20 | 21 | The element consists of the description of the question 22 | 23 | Each question has the following components 24 | 25 | ![Image](./images/question1.PNG) 26 | 27 | The contents are parsed and stored using Beautiful Soup, a library built for web scraping 28 | 29 | 30 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Questions_from_Project_Euler/images/euler_home.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Questions_from_Project_Euler/images/euler_home.PNG -------------------------------------------------------------------------------- /System-Automation-Scripts/Questions_from_Project_Euler/images/euler_questions.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Questions_from_Project_Euler/images/euler_questions.PNG -------------------------------------------------------------------------------- /System-Automation-Scripts/Questions_from_Project_Euler/images/question1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Questions_from_Project_Euler/images/question1.PNG -------------------------------------------------------------------------------- /System-Automation-Scripts/README.md: -------------------------------------------------------------------------------- 1 | # System-Automation-Scripts 2 | This folder conatin scripts about Operating system Automation with Linux and Windows shell comands. -------------------------------------------------------------------------------- /System-Automation-Scripts/Story Reader/Readme.md: -------------------------------------------------------------------------------- 1 | [![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com) 2 | 3 |
4 | 5 |
6 | 7 | # Audiobook 8 | 9 | Read any audio book from pdf using python. 10 | 11 | ### Modules used: 12 | 1. PyPDF2 13 | 2. Pyttsx3 14 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Story Reader/audiobook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Story Reader/audiobook.png -------------------------------------------------------------------------------- /System-Automation-Scripts/Story Reader/main.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | 3 | import pyttsx3 #pip install pyttsx3 4 | import PyPDF2 #pip install PyPDF2 5 | 6 | story = open('mybook.pdf', 'rb') #Name of your script make sure it's in pdf format 7 | pdfReader = PyPDF2.PdfFileReader(story) 8 | pages = pdfReader.numPages 9 | # pages = pdfReader.getPage(number) Replace nu,ber with any specific page number you want this to read 10 | engine = pyttsx3.init() 11 | voices = engine.getProperty('voices') 12 | engine.setProperty('voice', voices[0].id) #For male voice change the value to 1. 13 | 14 | for num in range(0, pages): 15 | page = pdfReader.getPage(num) 16 | text = page.extractText() 17 | engine.say(text) 18 | engine.runAndWait() -------------------------------------------------------------------------------- /System-Automation-Scripts/Story Reader/mybook.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Story Reader/mybook.pdf -------------------------------------------------------------------------------- /System-Automation-Scripts/Twitter Automation/README.md: -------------------------------------------------------------------------------- 1 |

Twitter Automation Code

2 |

Pre-requisites:

3 | -Must have a Twitter account and Twitter developer account.
4 | -Need to add your access keys to use twitter APIs
5 | 6 |

Working:

7 | Just run it and it will like and retweet tweets of the value which you have assigned to the "search". 8 | 9 |

Voila!!! Twitter Is Automated


10 | Here, I have given value as search = "#100DaysOfCode" 11 | 12 |


13 |

14 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Twitter Automation/Twitter Automation.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | #Importing Library 4 | import tweepy 5 | import time 6 | 7 | #Twitter Authentication APIs 8 | CONSUMER_KEY = '' 9 | CONSUMER_SECRET = '' 10 | ACCESS_KEY = '' 11 | ACCESS_SECRET = '' 12 | auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) 13 | auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) 14 | 15 | #Likes & Retweeting 16 | api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) 17 | user = api.me() 18 | search = '#india' 19 | numTweet = 500 20 | for tweet in tweepy.Cursor(api.search, search).items(numTweet): 21 | try: 22 | print('Tweet Liked') #Like 23 | tweet.favorite() 24 | print("Retweet done") #Retweet 25 | tweet.retweet() 26 | time.sleep(10) 27 | except tweepy.TweepError as e: 28 | print(e.reason) 29 | except StopIteration: 30 | break 31 | 32 | ##Press 'i' to stop iteration in jupyter notebook -------------------------------------------------------------------------------- /System-Automation-Scripts/Twitter Automation/twitter_image.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Twitter Automation/twitter_image.PNG -------------------------------------------------------------------------------- /System-Automation-Scripts/WhatsApp-message-automation/README.md: -------------------------------------------------------------------------------- 1 | # Automate-sending-WhatsApp-messages 2 | 3 | - This script can be used to send messages to your contacts on WhatsApp from your Command line!! 4 | 5 | ## Working ## 6 | - The URL, https://web.whatsapp.com/ needs to be opened and initiate. 7 | 8 | ![Image](qrcode.PNG) 9 | 10 | - On the right side there is a QR code which needs to be scanned in order to open WhatsApp over the web. 11 | 12 | ![Image](search.PNG) 13 | 14 | - The icon circled in the image is can be used to look for contacts/groups 15 | - The script is automated to click on the search button (circled button) 16 | 17 | ![Image](frequent.PNG) 18 | 19 | - On clicking the button, it opens into the above image. 20 | - Further, the name can be typed into the search bar. The ENTER key will be pressed by the script. 21 | - The chat of the entered contact will be opened. 22 | 23 | ![Image](abcd.PNG) 24 | 25 | - The script looks as shown below 26 | - Messages can be sent to more than one contact, 27 | - More than one message can be sent to the same contact 28 | 29 | ![Image](script.PNG) 30 | 31 | ![Image](confirm.png) 32 | -------------------------------------------------------------------------------- /System-Automation-Scripts/WhatsApp-message-automation/abcd.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/WhatsApp-message-automation/abcd.PNG -------------------------------------------------------------------------------- /System-Automation-Scripts/WhatsApp-message-automation/confirm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/WhatsApp-message-automation/confirm.png -------------------------------------------------------------------------------- /System-Automation-Scripts/WhatsApp-message-automation/frequent.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/WhatsApp-message-automation/frequent.PNG -------------------------------------------------------------------------------- /System-Automation-Scripts/WhatsApp-message-automation/qrcode.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/WhatsApp-message-automation/qrcode.PNG -------------------------------------------------------------------------------- /System-Automation-Scripts/WhatsApp-message-automation/script.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/WhatsApp-message-automation/script.PNG -------------------------------------------------------------------------------- /System-Automation-Scripts/WhatsApp-message-automation/search.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/WhatsApp-message-automation/search.PNG -------------------------------------------------------------------------------- /System-Automation-Scripts/Word detector/README.md: -------------------------------------------------------------------------------- 1 | ### Word Detector 2 | 3 | #### This script is used to detect whether a given word is present in a list of files.All the files which contain the specified word gets stored in a seperate folder. 4 | 5 | #### It takes two inputs - 6 | 7 | 1.Path of the directory which contains the files. 8 | 9 | [Sample path - "C:/Users//Desktop//"] 10 | 11 | 2.Word that you want to detect in these files. 12 | 13 | [Sample word - "awesome"] 14 | 15 | #### The output it produces - 16 | 17 | A seperate folder in the current directory which contains the target files(files that contain the input word). 18 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Word detector/word_detector.py: -------------------------------------------------------------------------------- 1 | import os 2 | import shutil 3 | 4 | # Inputs 5 | directory_path = input("Enter the absolute path of the folder: ") 6 | detect_this = input("Enter the word you want to detect in the files: ") 7 | 8 | # Condition to omit creation of the folder if it already exists. 9 | if f"Flagged_{detect_this}" not in os.listdir(directory_path): 10 | os.mkdir(f"Flagged_{detect_this}") 11 | 12 | # Creates a list of all the files/directories in the provided path 13 | files = os.listdir(directory_path) 14 | 15 | # To omit adding the python script and the folder in the list of files. 16 | files.remove(f"Flagged_{detect_this}") 17 | files.remove("detector.py") 18 | 19 | # List to collect the files which contains the target word 20 | flagged_files = [] 21 | 22 | # Logic to loop over the files and check for the presence of the target word in them and adding them to the flagged_files list. 23 | for file in files: 24 | with open(file, "r") as f: 25 | if detect_this.lower() in f.read().lower(): 26 | flagged_files.append(file) 27 | 28 | 29 | # Looping over the flagged files and moving them to a seperate folder 30 | for file in flagged_files: 31 | shutil.move(directory_path+file, directory_path + 32 | "Flagged_"+detect_this) 33 | 34 | # To make the output look organised 35 | print( 36 | f"The script was successfull in detecting {detect_this} in the list of files") 37 | print(" ") 38 | print("Summary of the detection: ") 39 | print(f"Total Files: {len(files)}") 40 | print(f"Files with the target word: {len(flagged_files)}") 41 | print(" ") 42 | print("Thanks for using this script..........") 43 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Zoom automation/Readme.md: -------------------------------------------------------------------------------- 1 | ## Zoom automation script 2 | This script will automatically attend Zoom Classes. The basic features are It accept the Meeting ID and Meeting Password from the Console and Opens the Zoom Class keeping Camera/Audio off. 3 | 4 | ## Setting up: 5 | 6 | ### Prerequisite: 7 | - Download the zoom desktop application from [here](https://zoom.us/download) 8 | - Make sure that the img folder and the script are in the same folder. 9 | 10 | ### Install the requirements using 11 | ```sh 12 | $ pip3 install pyautogui 13 | $ pip3 install opencv-python 14 | ``` 15 | 16 | ## Running the script: 17 | ```sh 18 | $ python3 zoom.py 19 | ``` 20 | -------------------------------------------------------------------------------- /System-Automation-Scripts/Zoom automation/img/join.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Zoom automation/img/join.png -------------------------------------------------------------------------------- /System-Automation-Scripts/Zoom automation/img/s1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Zoom automation/img/s1.png -------------------------------------------------------------------------------- /System-Automation-Scripts/Zoom automation/img/s2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Zoom automation/img/s2.png -------------------------------------------------------------------------------- /System-Automation-Scripts/Zoom automation/img/s3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/System-Automation-Scripts/Zoom automation/img/s3.png -------------------------------------------------------------------------------- /System-Automation-Scripts/Zoom automation/zoom.py: -------------------------------------------------------------------------------- 1 | ''' This script will automatically attend zoom meet 2 | ''' 3 | import time 4 | import pyautogui 5 | 6 | ID = input('Enter Meeting ID: ') 7 | PASSCODE = input('Enter Meeting password: ') 8 | DURATION = input('Enter total duration of meet in seconds') 9 | 10 | 11 | def autozoom(): 12 | # opening zoom app 13 | pyautogui.hotkey('alt', 'f2') 14 | time.sleep(5) 15 | pyautogui.write('zoom') 16 | pyautogui.press('enter', interval=0.5) 17 | time.sleep(5) 18 | # join button 19 | x_c, y_c = pyautogui.locateCenterOnScreen('img/join.png', confidence=0.9) 20 | time.sleep(5) 21 | pyautogui.click(x_c, y_c) 22 | # adding ID 23 | time.sleep(5) 24 | x_s, y_s = pyautogui.locateCenterOnScreen('img/s3.png', confidence=0.9) 25 | pyautogui.click(x_s, y_s) 26 | pyautogui.write(ID) 27 | # video off 28 | time.sleep(5) 29 | x_s, y_s = pyautogui.locateCenterOnScreen('img/s2.png', confidence=0.9) 30 | pyautogui.click(x_s, y_s) 31 | # audio off 32 | time.sleep(5) 33 | x_s, y_s = pyautogui.locateCenterOnScreen('img/s1.png', confidence=0.9) 34 | pyautogui.click(x_s, y_s) 35 | pyautogui.press('enter', interval=5) 36 | # entering a passcode 37 | pyautogui.write(PASSCODE) 38 | pyautogui.press('enter', interval=10) 39 | print('Hold (Ctrl+c) to exit the program ') 40 | 41 | # Total time of zoom session 42 | time.sleep(DURATION) 43 | 44 | # closing Zoom 45 | pyautogui.hotkey('alt', 'f4') 46 | time.sleep(0.5) 47 | pyautogui.hotkey('alt', 'f4') 48 | 49 | 50 | autozoom() 51 | -------------------------------------------------------------------------------- /System-Automation-Scripts/junk_organiser.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path as pt 3 | 4 | DIRECTORIES = { 5 | "HTML": [".html5", ".html", ".htm", ".xhtml"], 6 | "IMAGES": [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", "svg", 7 | ".heif", ".psd"], 8 | "VIDEOS": [".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", ".vob", ".mng", 9 | ".qt", ".mpg", ".mpeg", ".3gp"], 10 | "DOCUMENTS": [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods", 11 | ".odt", ".pwi", ".xsn", ".xps", ".dotx", ".docm", ".dox", 12 | ".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx", ".ppt", 13 | "pptx"], 14 | "ARCHIVES": [".a", ".ar", ".cpio", ".iso", ".tar", ".gz", ".rz", ".7z", 15 | ".dmg", ".rar", ".xar", ".zip"], 16 | "AUDIO": [".aac", ".aa", ".aac", ".dvf", ".m4a", ".m4b", ".m4p", ".mp3", 17 | ".msv", "ogg", "oga", ".raw", ".vox", ".wav", ".wma"], 18 | "PLAINTEXT": [".txt", ".in", ".out"], 19 | "PDF": [".pdf"], 20 | "PYTHON": [".py"], 21 | "C": [".c"], 22 | "CPP": [".cpp"], 23 | "JAVA": [".java"], 24 | "XML": [".xml"], 25 | "EXE": [".exe"], 26 | "SHELL": [".sh"] 27 | 28 | } 29 | 30 | FILE_FORMATS = {file_format: directory 31 | for directory, file_formats in DIRECTORIES.items() 32 | for file_format in file_formats} 33 | 34 | def org_junk(): 35 | for entry in os.scandir(): 36 | if entry.is_dir(): 37 | continue 38 | file_path = pt(entry) 39 | file_format = file_path.suffix.lower() 40 | if file_format in FILE_FORMATS: 41 | directory_path = pt(FILE_FORMATS[file_format]) 42 | directory_path.mkdir(exist_ok=True) 43 | file_path.rename(directory_path.joinpath(file_path)) 44 | 45 | for dir in os.scandir(): 46 | try: 47 | os.rmdir(dir) 48 | except: 49 | pass 50 | 51 | if __name__ == "__main__": 52 | org_junk() 53 | -------------------------------------------------------------------------------- /System-Automation-Scripts/pdfCreator.py: -------------------------------------------------------------------------------- 1 | #! python3 2 | import PyPDF2 3 | # Creating dict in order to gather all info at one place 4 | pdf={} 5 | # Nmber of PDF files are requre to make new pdf 6 | numPdf = input('Type number of PDF files you want to copy in a new PDF : ') 7 | for i in range(numPdf): 8 | # Sequence or order of PDF files in new a new pdf file 9 | b=input('Type sequence of this Pdf you want in a new Pdf in numeric order : ') 10 | """if b in seq: 11 | print('This sequence already exist. Try new sequence...') 12 | i = i 13 | continue 14 | elif b>numPdf: 15 | print('Sequence order is out of range. Try another...') 16 | i=i 17 | continue""" 18 | a=raw_input('Type Pdf name if it is in same folder : ') 19 | print('Number of pages you want to copy from this pdf ') 20 | s=input('Type Starting Page Number you want and page number starts from 1 : ') 21 | e= input('Type Last Page Number you want : ') 22 | pdf.setdefault(b, {}) 23 | pdf[b].setdefault(a, {'start':s-1, 'end':e-1}) 24 | writingPdf=PyPDF2.PdfFileWriter() 25 | for i in range(1, numPdf+1): 26 | for k in pdf[i].keys(): 27 | openPdf=open(k, 'rb') 28 | readingPdf=PyPDF2.PdfFileReader(openPdf) 29 | 30 | for t in range(pdf[i][k]['start'], pdf[i][k]['end']+1): 31 | copyPdf=readingPdf.getPage(t) 32 | writingPdf.addPage(copyPdf) 33 | 34 | newPdf=open('new_Pdf.pdf', 'wb') 35 | writingPdf.write(newPdf) 36 | newPdf.close() 37 | """for l in range (numPdf): 38 | pdf[bi].keys().close() 39 | """ 40 | -------------------------------------------------------------------------------- /System-Automation-Scripts/processClose.py: -------------------------------------------------------------------------------- 1 | """ 2 | When using system for general purposes, users do not need some 3 | processes such as mysql, apache etc which are installed during 4 | development and some other backends running unnecessarily in 5 | background. These processes can be stopped for that login. 6 | 7 | This script ends these running services only for that login session. 8 | 9 | Note:- These processes will run normally when user logins again and 10 | this script only stops the mentioned running services. 11 | """ 12 | 13 | # Base library to access system 14 | import os 15 | 16 | # List of services user wishes to close on login. 17 | # REMOVE the existing and add your own desired services as strings. 18 | services = ["mysql", "mongod", "docker"] # Sample 19 | 20 | # Execute "$ sudo service ## stop" command 21 | for i in services: 22 | os.system("sudo service " + i + " stop") 23 | 24 | # Print the total services stopped 25 | print(str(len(services)) + " services stopped.") 26 | -------------------------------------------------------------------------------- /System-Automation-Scripts/pypdf.py: -------------------------------------------------------------------------------- 1 | #!/usrbin/python3 2 | # Automation with pdf file 3 | # Script design just to automate stuffs with pdf file 4 | import PyPDF2 5 | import os 6 | print(os.system('pyfiglet pypdf')) 7 | pdFileObj = open('Exam-Transcript.pdf','rb') 8 | #open pdf file in read binary mode(rb) & store in pdfFileObj 9 | pdfReader = PyPDF2.PdfFileReader(pdFileObj) 10 | #pdfFileReader represents pdf file 11 | print(pdfReader.numPages) 12 | #to check number of pages in you pdf file use .numPages() 13 | pageObj = pdfReader.getPage(0) 14 | print(pageObj.extractText()) #extract the pdf data in text format 15 | -------------------------------------------------------------------------------- /System-Automation-Scripts/verify_email.py: -------------------------------------------------------------------------------- 1 | # This script checks whether the email address is existing or not. 2 | # Using Python 3 3 | import socket 4 | import smtplib 5 | 6 | # Getting local server hostname 7 | host = socket.gethostname() 8 | 9 | # SMTP lib setup 10 | server = smtplib.SMTP() 11 | server.set_debuglevel(0) 12 | 13 | # SMTP Conversation 14 | server.connect(mxRecord) 15 | server.helo(host) 16 | server.mail('me@domain.com') 17 | code, message = server.rcpt(str(addressToVerify)) 18 | server.quit() 19 | 20 | # Assume 250 as Success 21 | if code == 250: 22 | print('Success') 23 | else: 24 | print('Failed') -------------------------------------------------------------------------------- /System-Automation-Scripts/zipFileConverter.py: -------------------------------------------------------------------------------- 1 | #! python3 2 | #script for converting file into ZIP file 3 | import os , zipfile 4 | # type folder path where your zip file is kept 5 | os.chdir('Enter text file Path') 6 | #type the file name you want for ZIP file 7 | newZipFile=zipfile.ZipFile('new_zip_file.zip', 'w') 8 | #type file name you want to convert into ZIP file 9 | newZipFile.write('example_text_file_name.txt', compress_type=zipfile.ZIP_DEFLATED) 10 | newZipFile.close() 11 | #it will save new zip file in same folder 12 | -------------------------------------------------------------------------------- /System-Automation-Scripts/zipFileExtracterCommandLine.py: -------------------------------------------------------------------------------- 1 | #! python27 2 | import sys , os , zipfile 3 | # Command line argument 4 | # First type Program name then Zip folder path and then type ZIP File name 5 | sys.argv 6 | # it take second argument of CMD i.e Folder path 7 | os.chdir(sys.argv[1]) 8 | # it takes third argument of cmd Zip File Name with extention ( .zip) 9 | yourZip=zipfile.ZipFile(sys.argv[2]) 10 | # It extract Zip File 11 | yourZip.extractall() 12 | yourZip.close() 13 | -------------------------------------------------------------------------------- /Web-Scraping/Covid-19 Statics/README.md: -------------------------------------------------------------------------------- 1 |

Scraping Covid-19 Statics

2 | 3 | Scraping the corona virus cases of 213 countries and territories. 4 | Using Beautiful soup python package to extract the HTML content of the website(https://www.worldometers.info/coronavirus/countries-where-coronavirus-has-spread/). 5 | 6 | Representing the extracted data in table format form using texttable python library. 7 | -------------------------------------------------------------------------------- /Web-Scraping/Covid-19 Statics/code.py: -------------------------------------------------------------------------------- 1 | # Importing Libraries 2 | import requests 3 | from bs4 import BeautifulSoup 4 | import texttable as tt 5 | 6 | # URL for scrapping data 7 | url = 'https://www.worldometers.info/coronavirus/countries-where-coronavirus-has-spread/' 8 | 9 | # Get URL html 10 | page = requests.get(url) 11 | soup = BeautifulSoup(page.text, 'html.parser') 12 | 13 | data = [] 14 | 15 | # soup.find_all('td') will scrape every element in the url's table 16 | data_iterator = iter(soup.find_all('td')) 17 | # data_iterator is the iterator of the table 18 | 19 | # This loop will keep repeating till there is data available in the iterator 20 | while True: 21 | try: 22 | country = next(data_iterator).text 23 | confirmed = next(data_iterator).text 24 | deaths = next(data_iterator).text 25 | continent = next(data_iterator).text 26 | deaths=deaths.replace(',','') #Removing "," from deaths string 27 | confirmed=confirmed.replace(',','') #Removing "," from confirmed string 28 | 29 | # For 'confirmed' and 'deaths', make sure to remove the commas and convert to int 30 | data.append(( 31 | country, 32 | int(confirmed), #Converting string to int 33 | int(deaths), #Converting string to int 34 | continent 35 | )) 36 | 37 | # StopIteration error is raised when there are no more elements left to iterate through 38 | except StopIteration: 39 | break 40 | 41 | # Sort the data by the number of confirmed cases 42 | data.sort(key = lambda row: row[1], reverse = True) 43 | 44 | # Creating Table 45 | table = tt.Texttable() 46 | table.add_rows([(None, None, None, None)] + data) # Add an empty row at the beginning for the headers 47 | table.set_cols_align(('c', 'c', 'c', 'c')) # 'l' denotes left, 'c' denotes center, and 'r' denotes right 48 | table.header((' Country ', ' Number of cases ', ' Deaths ', ' Continent ')) 49 | 50 | # Printing the created table 51 | print(table.draw()) 52 | 53 | -------------------------------------------------------------------------------- /Web-Scraping/Cricbuzz Scrap/Readme.md: -------------------------------------------------------------------------------- 1 | # Cricbuzz srapper 2 | 3 | This python script will scrap cricbuzz.com to get live scores. 4 | 5 | ## Technologies used: 6 | - urllib.request 7 | - BeautifulSoup 8 | -------------------------------------------------------------------------------- /Web-Scraping/Cricbuzz Scrap/crik_buzz.py: -------------------------------------------------------------------------------- 1 | from urllib.request import urlopen 2 | from bs4 import BeautifulSoup 3 | 4 | URL = 'http://www.cricbuzz.com/cricket-match/live-scores' 5 | page = urlopen(URL) 6 | soup = BeautifulSoup(page,'html.parser') 7 | 8 | update=[] 9 | 10 | for score in soup.find_all('div',attrs={'class':'cb-col cb-col-100 cb-lv-main'}): 11 | s=score.text.strip() 12 | update.append(s) 13 | 14 | for i in range(len(update)): 15 | print(i+1), 16 | print(update[i]) 17 | 18 | -------------------------------------------------------------------------------- /Web-Scraping/E-Commerce Website/README.md: -------------------------------------------------------------------------------- 1 | # WebScrap 2 | 3 | Web scraping (web harvesting or web data extraction) is data scraping used for extracting data from websites. Web scraping software may access the World Wide Web directly using the Hypertext Transfer Protocol, or through a web browser. 4 | 5 | In this repo Web Scraping is done on an E-Commerce Website using BeautifulSoup in [Python](https://www.python.org/) 6 | 7 | [Beautiful Soup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) 8 | * Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. It commonly saves programmers hours or days of work. 9 | 10 | -------------------------------------------------------------------------------- /Web-Scraping/E-Commerce Website/WebScraping.py: -------------------------------------------------------------------------------- 1 | import bs4 2 | from urllib.request import urlopen 3 | from bs4 import BeautifulSoup as soup 4 | 5 | my_url = 'https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=graphics%20card' 6 | 7 | # opening url and grabbing the web page 8 | uClient = urlopen(my_url) 9 | page_html = uClient.read() 10 | uClient.close() 11 | 12 | # html parsing 13 | page_soup = soup(page_html, 'html.parser') 14 | 15 | # grabbing all containers with class name = item-container 16 | containers = page_soup.findAll('div', {'class':'item-container'}) 17 | 18 | filename = "products.csv" 19 | f = open(filename, 'w') 20 | 21 | headers = "brands, product_name, shipping\n" 22 | 23 | f.write(headers) 24 | 25 | container = containers[1] 26 | 27 | for container in containers: 28 | brand = container.div.div.a.img['title'] 29 | title_container = container.findAll('a', {'class':'item-title'}) 30 | product_name = title_container[0].text 31 | ship_container = container.findAll('li', {'class':'price-ship'}) 32 | # use strip() to remove blank spaces before and after text 33 | shipping = ship_container[0].text.strip() 34 | 35 | print("brand:" + brand) 36 | print("product_name:" + product_name) 37 | print("shipping:" + shipping) 38 | 39 | f.write(brand + ',' + product_name.replace(',' , '|') + ',' + shipping + '\n') 40 | 41 | f.close() 42 | 43 | -------------------------------------------------------------------------------- /Web-Scraping/E-Commerce Website/products.csv: -------------------------------------------------------------------------------- 1 | brands, product_name, shipping 2 | GIGABYTE,GIGABYTE GeForce GTX 1070 DirectX 12 GV-N1070WF2OC-8GD Video Cards,Free Shipping 3 | EVGA,EVGA GeForce GTX 1080 SC GAMING ACX 3.0| 08G-P4-6183-KR| 8GB GDDR5X| LED| DX12 OSD Support (PXOC),Free Shipping 4 | XFX,XFX Radeon RX 470 RS Triple X DirectX 12 RX-470P436BM 4GB 256-Bit GDDR5 PCI Express 3.0 CrossFireX Support Video Card,$3.99 Shipping 5 | ASUS,ASUS Radeon RX 480 DirectX 12 DUAL-RX480-O8G Video Card,$4.99 Shipping 6 | ZOTAC,ZOTAC GeForce GTX 1080 Ti AMP Edition 11GB GDDR5X 352-bit Gaming Graphics Card VR Ready 16+2 Power Phase Freeze Fan Stop IceStorm Cooling Spectra Lighting ZT-P10810D-10P,$6.99 Shipping 7 | ASUS,ASUS ROG GeForce GTX 1080 STRIX-GTX1080-A8G-GAMING Video Card,Free Shipping 8 | EVGA,EVGA GeForce GTX 1070 SC GAMING ACX 3.0 Black Edition| 08G-P4-5173-KR| 8GB GDDR5| LED| DX12 OSD Support (PXOC),Free Shipping 9 | GIGABYTE,GIGABYTE Radeon RX 480 G1 Gaming 4GB GV-RX480G1GAMING-4GD Video Card,$4.99 Shipping 10 | XFX,XFX Radeon RS RX 480 DirectX 12 RX-480P836BM 8GB 256-Bit GDDR5 PCI Express 3.0 CrossFireX Support Video Card,$4.99 Shipping 11 | ZOTAC,ZOTAC GeForce GTX 1070 Mini| ZT-P10700G-10M| 8GB GDDR5,Free Shipping 12 | MSI,MSI Radeon RX 480 DirectX 12 Radeon RX 480 4G Video Card,$4.99 Shipping 13 | XFX,XFX Radeon GTR RX 480 DirectX 12 RX-480P8DBA6 Black Edition Video Card,$4.99 Shipping 14 | -------------------------------------------------------------------------------- /Web-Scraping/Hacktoberfest_Events/README.md: -------------------------------------------------------------------------------- 1 | ## Hacktoberfest Events 2 | 3 | ### This script scrapes all the events from the Hacktoberfest events website and stores them in a csv file. 4 | 5 | ### How to use this script? 6 | 7 | 1. Make sure all the requirements for the script are present in your system by running: 8 | 9 | pip install -r requirements.txt 10 | 11 | 2. Run the following command: 12 | 13 | python hacktoberfest_events.py 14 | 15 | ### Author 16 | 17 | [Aditya Jetely](https://github.com/AdityaJ7) -------------------------------------------------------------------------------- /Web-Scraping/Hacktoberfest_Events/hacktoberfest_events.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup as bs 3 | import pandas as pd 4 | 5 | 6 | def scrape_tablerows(): 7 | """This function scrapes the tablerows related to our target elements. 8 | Our target element here are the events of hactoberfest. 9 | 10 | Returns: 11 | tablerows[list]: A list of tablerows of our taget elements. 12 | """ 13 | hacktoberfest_events_url = "https://hacktoberfest.digitalocean.com/events" 14 | response = requests.get(hacktoberfest_events_url) 15 | soup = bs(response.content, 'html.parser') 16 | mydivs = soup.findAll("tbody", {"class": "list"}) 17 | tablerows = mydivs[0].findAll("tr") 18 | return tablerows 19 | 20 | 21 | def hacktoberfest_events(tablerows): 22 | """This function takes the list of tablerows as input and performs 23 | scraping of required elements as well as stores the scraped data 24 | into a csv file. 25 | 26 | Args: 27 | tablerows (list): Lis of tablerows of the target elements. 28 | """ 29 | events = {} 30 | for i, tablerow in enumerate(tablerows): 31 | location = tablerow.find("td", {"class": "location"}).text 32 | link = tablerow.find("a")['href'] 33 | name = tablerow.find("td", {"class": "event_name"}).text.strip() 34 | date = tablerow.find("td", {"class": "date is-hidden"}).text.strip() 35 | events[i] = [name, date, location, link] 36 | df1 = pd.DataFrame.from_dict(events, orient='index') 37 | df1.columns = ['Name', 'Date', 'Location', 'Link'] 38 | df1.to_csv('hacktoberfest_events.csv') 39 | 40 | 41 | if __name__ == "__main__": 42 | tablerows = scrape_tablerows() 43 | hacktoberfest_events(tablerows) 44 | print("The events have been stored successfully") 45 | -------------------------------------------------------------------------------- /Web-Scraping/Hacktoberfest_Events/requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4==4.9.1 2 | certifi==2020.6.20 3 | chardet==3.0.4 4 | idna==2.10 5 | requests==2.24.0 6 | soupsieve==2.0.1 7 | urllib3==1.25.10 8 | pandas==1.1.2 -------------------------------------------------------------------------------- /Web-Scraping/IMDB_TopMovies/README.md: -------------------------------------------------------------------------------- 1 | # Scrap Top Movies from IMDB 2 | 3 | ### This Python script will Scrap the details of top 250 movies from IMDB and generate a CSV file for it 4 | 5 | ### Technologies used: 6 | - pandas 7 | - BeautifulSoup 8 | -------------------------------------------------------------------------------- /Web-Scraping/IMDB_TopMovies/imdb_topmovies.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """IMDB_Topmovies.ipynb 3 | """ 4 | 5 | #scrap top 250 movies from IMDB and generate a CSV file for it using beautifulsoup 6 | 7 | from bs4 import BeautifulSoup 8 | import requests 9 | import re 10 | import pandas as pd 11 | 12 | url = 'http://www.imdb.com/chart/top' 13 | response = requests.get(url) 14 | soup = BeautifulSoup(response.text, 'html') 15 | 16 | movies = soup.select('td.titleColumn') 17 | stars = [a.attrs.get('title') for a in soup.select('td.titleColumn a')] 18 | ratings = [round(float(b.attrs.get('data-value')),1) for b in soup.select('td.posterColumn span[name=ir]')] 19 | 20 | imdb = [] 21 | 22 | # Store each item into dictionary (data), then put those into a list (imdb) 23 | for index in range(0, len(movies)): 24 | movie_string = movies[index].get_text() 25 | movie = (' '.join(movie_string.split()).replace('.', '')) 26 | movie_title = movie[len(str(index))+1:-7] 27 | year = re.search('\((.*?)\)', movie_string).group(1) 28 | data = {"movie_title": movie_title, 29 | "year": year, 30 | "star_cast": stars[index], 31 | "rating": ratings[index], 32 | } 33 | imdb.append(data) 34 | 35 | # CREATING A DATAFRAME 36 | df = pd.DataFrame(imdb) 37 | df.index = df.index.rename('S.No') 38 | #copy data frame in to CSV file 39 | #csv file has been created in current working directory 40 | df.to_csv('imdb.csv') 41 | #read=pd.read_csv('/content/imdb.csv') 42 | #print(read) 43 | -------------------------------------------------------------------------------- /Web-Scraping/Instagram-scraper/README.md: -------------------------------------------------------------------------------- 1 | # Instagram scraper 2 | Instagram scraper is a python script which helps in extracting data from instagram users data 3 | 4 | 5 | ## Libraries used 6 | urllib is a python library used to send request used to website to retrive html content 7 | 8 | bs4 is used to extract data from html content 9 | 10 | Note: This script will only work for public accounts -------------------------------------------------------------------------------- /Web-Scraping/Instagram-scraper/instagram-scraper.py: -------------------------------------------------------------------------------- 1 | #Import all libraries 2 | from bs4 import BeautifulSoup 3 | from urllib.request import Request, urlopen 4 | 5 | # instagram URL 6 | URL="https://www.instagram.com/" 7 | 8 | def scrape_data(): 9 | username = input("Enter the instagram username ") 10 | url=URL+username 11 | 12 | # Sending request to server using Urllib 13 | req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) 14 | html_data = urlopen(req).read() 15 | 16 | #Beautyfying all data to html form 17 | soup=BeautifulSoup(html_data,'html.parser') 18 | 19 | #Search for meta tag with description of og:description 20 | data = soup.find("meta", property="og:description").attrs['content'] 21 | 22 | # Split content based on - element 23 | data = data.split("-")[0] 24 | 25 | # Adding data to user dictionary 26 | user_data={} 27 | data = data.split(" ") 28 | user_data['Followers'] = data[0] 29 | user_data['Following'] = data[2] 30 | user_data['Posts'] = data[4] 31 | 32 | return user_data 33 | 34 | 35 | if __name__=="__main__": 36 | data=scrape_data() 37 | print("User has "+data['Followers']+ " Followers") 38 | print("User is following "+data['Following']+ " peoples") 39 | print("User has "+data['Posts']+ " Posts") 40 | -------------------------------------------------------------------------------- /Web-Scraping/Instagram/README.md: -------------------------------------------------------------------------------- 1 | # INSTAGRAM SCRAPPER 2 | 3 | ### Instagram_count 4 | 5 | - This Script counts the number of followings, followers and posts. 6 | - Takes the username from the terminal and shows them the output. 7 | 8 | -------------------------------------------------------------------------------- /Web-Scraping/Instagram/instagram_count.py: -------------------------------------------------------------------------------- 1 | from bs4 import BeautifulSoup 2 | import requests 3 | 4 | #The instagram URL 5 | URL="https://www.instagram.com/{}/" 6 | username = input(" Enter the instagram username ") 7 | 8 | #request a response from the URL 9 | response = requests.get(URL.format(username)) 10 | # scraping the contents 11 | soup = BeautifulSoup(response.text,"html.parser") 12 | #The contents of the meta tag with the property og:description are accessed here 13 | meta_content = soup.find("meta", property="og:description") 14 | #print(meta_content) 15 | data = {} 16 | content = meta_content.attrs['content'] 17 | content = content.split("-")[0] 18 | content = content.split(" ") 19 | 20 | data['Followers'] = content[0] 21 | data['Following'] = content[2] 22 | data['Posts'] = content[4] 23 | 24 | print(username + " has " + data["Followers"]+" followers, "+ data["Following"]+" following, "+ data["Posts"]+" posts ") 25 | 26 | 27 | ''' 28 | output: 29 | Enter the instagram username "ferrari" 30 | ferrari has 19m followers, 5 following, 2,538 posts 31 | ''' 32 | -------------------------------------------------------------------------------- /Web-Scraping/Medium-Articles-Details-Scrapping/.gitignore: -------------------------------------------------------------------------------- 1 | # Unnecesaary Files 2 | 3 | app/__pycahce__/ 4 | .idea -------------------------------------------------------------------------------- /Web-Scraping/Medium-Articles-Details-Scrapping/README.md: -------------------------------------------------------------------------------- 1 | # Medium-Articles-Details-Scrapping 2 | This script will scrap details about medium articles published in a date range in the given publication. The dates are choosen randomly. If there is no article on that date, then that date is skipped. The results returned is a dataframe which can be saved in any format, currently saves as CSV. Here is the preview of the terminal: 3 | ![](terminal-preview.PNG) 4 | 5 | # Requirements 6 | - numpy 7 | - pandas 8 | - bs4 9 | - requests 10 | 11 | # How to run? 12 | - Run the command: python run.py 13 | 14 | # About the Scrap class 15 | A Scrapper to get details about medium articles published in a date range in a Publication by selecting random dates. 16 | 17 | Attributes 18 | ---------- 19 | urls_dict : dict 20 | key-value pairs of the publication name with link. Example: 21 | urls_dict={"The Startup":"https://medium.com/swlh"} 22 | 23 | start_date : str 24 | starting date of the search. Default: 2020-01-01 25 | 26 | end_date : str 27 | ending date of the search. Default: 2020-08-01 28 | 29 | year : int 30 | year in which search has to be done. Default: 2020 31 | 32 | number: int 33 | number of random dates you want to pick. Default: 10 34 | 35 | Methods 36 | ------- 37 | scrap(): 38 | Scrapping process will be initiated by this method. 39 | 40 | dataframe(): 41 | Returns the dataframe object. 42 | 43 | -------------------------------------------------------------------------------- /Web-Scraping/Medium-Articles-Details-Scrapping/run.py: -------------------------------------------------------------------------------- 1 | from app import Scrap 2 | 3 | print('-----------------') 4 | pub_name = input('Enter the comma seperated list of publication names(The Startup, Medium ...): ').split(',') 5 | pub_link = input('Enter the comma seperated links of publications (https://medium.com/swlh, https://towardsdatascience.com ...): ').split(',') 6 | 7 | if len(pub_name) != len(pub_link): 8 | print('Please Enter links of all publications!') 9 | 10 | pub_dict = {i: j for i, j in zip(pub_name, pub_link)} 11 | 12 | choice = input("The default information passed is:\nNumber=5\nstart_date='2019-01-01'\nend_date='2019-08-01'\nyear=2019\n\nDo you want to change it? (Y/N): ") 13 | 14 | if choice == 'Y': 15 | s_date = input("Enter new start date in format (YYYY-MM-DD): ") 16 | e_date = input("Enter new end date in format (YYYY-MM-DD): ") 17 | new_year = int(input("Enter year: ")) 18 | num = int(input("Enter number of random samples: ")) 19 | else: 20 | s_date = '2019-01-01' 21 | e_date = '2019-08-01' 22 | new_year = 2020 23 | num = 5 24 | 25 | print('Process started ...') 26 | a = Scrap(urls_dict=pub_dict, number=num, start_date=s_date, end_date=e_date, year=new_year) 27 | a.scrap() 28 | a.dataframe().to_csv('results.csv') 29 | print(a.dataframe()) 30 | print('-----------------') 31 | print('Process ended... Thanks for using!') 32 | -------------------------------------------------------------------------------- /Web-Scraping/Medium-Articles-Details-Scrapping/terminal-preview.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Web-Scraping/Medium-Articles-Details-Scrapping/terminal-preview.PNG -------------------------------------------------------------------------------- /Web-Scraping/Medium_article_downloader/Article_downloader.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | #Imports and dependencies 4 | 5 | import requests 6 | from bs4 import BeautifulSoup 7 | 8 | def download_article(): 9 | 10 | #The content is written into a text file 11 | 12 | file = open("Medium_article_content.txt", "w") 13 | 14 | #The URL of the article is entered here 15 | page_url = input("Enter the URL of the Medium Article ") 16 | 17 | #On looking for "my user agent", can be used to retrieve the value" 18 | headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0'} 19 | 20 | response = requests.get(page_url) 21 | 22 | soup = BeautifulSoup(response.text,"html.parser") 23 | 24 | #The content of the article is stored in the
tag 25 | 26 | for line in soup.find('article').find('div'): 27 | 28 | #All the content is essentially stored between

tags 29 | 30 | for content in line.find_all('p'): 31 | 32 | #contents are written into a file 33 | 34 | file.write(content.text + '\n') 35 | 36 | file.close() 37 | 38 | if __name__ == "__main__": 39 | download_article() 40 | -------------------------------------------------------------------------------- /Web-Scraping/Medium_article_downloader/README.md: -------------------------------------------------------------------------------- 1 | # Medium Article Downloader # 2 | 3 | ![Image](medium.PNG) 4 | 5 | Medium is a treasure trove of knowledge. It is a great place to read and write blogs 6 | 7 | Through this script, the contents of a medium article can be downloaded and stored 8 | 9 | The script is written in Python 10 | 11 | The Beautiful Soup library in Python enables web scraping and enables parsing though html content, which web pages are made of. Here, the same has been used. 12 | 13 | ## Implementation ## 14 | 15 | - The user is prompted to enter the URL of the Medium article that has to be downloaded 16 | 17 | - The contents are then stored in a file named Medium$_article$_content.txt 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Web-Scraping/Medium_article_downloader/medium.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Web-Scraping/Medium_article_downloader/medium.PNG -------------------------------------------------------------------------------- /Web-Scraping/Movie Recommendation/README.md: -------------------------------------------------------------------------------- 1 |

Movie Recommendation based on user emotions

2 | Here I am scraping all the movie titles of the genre corresponding to the input emotion and then output the list to the user. 3 | The movie titles are scraped from the IMDb list by using BeautifulSoup Python Library to recommend to the user. 4 | 5 | There are 8 classes of emotion that would be effective to classify a text these are:
6 | Anger
7 | Anticipation
8 | Disgust
9 | Fear
10 | Joy
11 | Sad
12 | Surprise
13 | Trust
14 | Here these are taken as input and the corresponding movies would be displayed for the emotion. 15 | 16 | ![IMG_20201002_003025](https://user-images.githubusercontent.com/43890931/94852005-e0c28b80-0446-11eb-8026-0bcb29b4703d.jpg) 17 | -------------------------------------------------------------------------------- /Web-Scraping/Questions_from_Project_Euler/README.md: -------------------------------------------------------------------------------- 1 | # Project Euler # 2 | 3 | ![Image](./images/euler_home.PNG) 4 | 5 | Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve 6 | 7 | This script written in Python, gets all the 700+ questions across 15 pages which is written into a CSV file named Project_Euler.csv 8 | 9 | Beautiful Soup is used for scraping the URL : https://projecteuler.net/archives 10 | 11 | Regular expressions have also been used in order to obtain the description of the questions 12 | 13 | ## Implementation ## 14 | 15 | Using **inspect element**, the contents of the page can be understood 16 | 17 | The structure of each page is as shown 18 | 19 | ![Image](./images/euler_questions.PNG) 20 | 21 | The element consists of the description of the question 22 | 23 | Each question has the following components 24 | 25 | ![Image](./images/question1.PNG) 26 | 27 | The contents are parsed and stored using Beautiful Soup, a library built for web scraping 28 | 29 | 30 | -------------------------------------------------------------------------------- /Web-Scraping/Questions_from_Project_Euler/images/euler_home.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Web-Scraping/Questions_from_Project_Euler/images/euler_home.PNG -------------------------------------------------------------------------------- /Web-Scraping/Questions_from_Project_Euler/images/euler_questions.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Web-Scraping/Questions_from_Project_Euler/images/euler_questions.PNG -------------------------------------------------------------------------------- /Web-Scraping/Questions_from_Project_Euler/images/question1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Web-Scraping/Questions_from_Project_Euler/images/question1.PNG -------------------------------------------------------------------------------- /Web-Scraping/README.md: -------------------------------------------------------------------------------- 1 | # Web-Scraping 2 | Web scraping is about downloading structured data from the web, selecting some of that data, and passing along what you selected to another process. This folder contains scripts related to web scraping with the help BeautifulSoup , Scrapy , Requests library. 3 | -------------------------------------------------------------------------------- /Web-Scraping/Reddit Scrapper/.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .vscode -------------------------------------------------------------------------------- /Web-Scraping/Reddit Scrapper/README.md: -------------------------------------------------------------------------------- 1 | # Reddit Data Scrapper 2 | This script will fetch the details of the Subreddit using Reddit API. You can define number of post you want to grab from each subreddit, the type of post you want: New ,Rising, Hot, Top, or Controversial, and the subreddits from which want details. The following details will be scrapped from each post: 'ID', 'Author', 'Title', 'Score', 'Subreddit_Name', 'Url', 'Number_of_Comments', 'Upvote_Ratio', 'Post_Body', 'Date'. 3 | 4 | # How to run? 5 | Run the command: 6 | 7 | ```python app.py``` 8 | 9 | and follow the on-screen instructions 10 | 11 | # Pre-requestes: 12 | Run this command: 13 | 14 | ```pip install requirements.txt``` 15 | 16 | # Working Demo: 17 | On configuring the following things: 18 | 19 | ![](output/config.PNG) 20 | 21 | The output csv looks like this: 22 | 23 | ![](output/csv.PNG) 24 | 25 | -------------------------------------------------------------------------------- /Web-Scraping/Reddit Scrapper/app.py: -------------------------------------------------------------------------------- 1 | import praw 2 | import pandas as pd 3 | import datetime as dt 4 | 5 | 6 | print("----------Set your preferences---------") 7 | client_id = input("Enter your client ID of Reddit app: ") 8 | client_secret = input("Enter your client secret of Reddit app: ") 9 | user_agent = input("Enter your user agent: ") 10 | subreddits = input("Enter comma seperated list of subreddits you want to scrape (Jokes, soccer, news...): ").split(',') 11 | limit = int(input("Enter how many post you want from each subreddit: ")) 12 | type_of_post = input("Enter the catergory of post you want to scrape (new,rising, hot, top, or controversial): ") 13 | 14 | reddit = praw.Reddit(client_id=client_id, 15 | client_secret=client_secret, 16 | user_agent=user_agent) # Reddit instance 17 | 18 | 19 | print('Now sit back and wait for process to complete...') 20 | data = [] 21 | for sub in subreddits: 22 | print(f"Currently Scrapping {sub}") 23 | if type_of_post == 'hot': 24 | posts = reddit.subreddit(sub).hot(limit=limit) 25 | elif type_of_post == 'new': 26 | posts = reddit.subreddit(sub).new(limit=limit) 27 | elif type_of_post == 'rising': 28 | posts = reddit.subreddit(sub).rising(limit=limit) 29 | elif type_of_post == 'top': 30 | posts = reddit.subreddit(sub).top(limit=limit) 31 | elif type_of_post == 'controversial': 32 | posts = reddit.subreddit(sub).controversial(limit=limit) 33 | else: 34 | print("Wrong Type of post selected!") 35 | break 36 | for post in posts: 37 | data.append([post.id, post.author, post.title, post.score, post.subreddit, post.url, post.num_comments, post.upvote_ratio, post.selftext, post.created]) 38 | 39 | 40 | dataframe = pd.DataFrame(data, columns=['ID', 'Author', 'Title', 'Score', 'Subreddit_Name', 'Url', 'Number_of_Comments', 'Upvote_Ratio', 'Post_Body', 'Date']) 41 | dataframe['Date'] = dataframe.Date.apply(lambda x: dt.datetime.fromtimestamp(x)) 42 | dataframe.to_csv('result.csv') 43 | print("Scrapping Done! Check the result.csv") -------------------------------------------------------------------------------- /Web-Scraping/Reddit Scrapper/output/config.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Web-Scraping/Reddit Scrapper/output/config.PNG -------------------------------------------------------------------------------- /Web-Scraping/Reddit Scrapper/output/csv.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Web-Scraping/Reddit Scrapper/output/csv.PNG -------------------------------------------------------------------------------- /Web-Scraping/Reddit Scrapper/requirements.txt: -------------------------------------------------------------------------------- 1 | praw==7.1.0 2 | pandas==1.1.1 -------------------------------------------------------------------------------- /Web-Scraping/ScrappingHackerNewsWebsite/README.md: -------------------------------------------------------------------------------- 1 | # Scraping Hacker news Website 2 | 3 | Scraping the first 2 pages of Hacker news website wherein user can read Tech news(as a articles) which has upvotes more than 100 with help of Requests and 4 | Beautiful Soup Modules. User can just click on story link to see the article. 5 | 6 | Link for Hacker news Website - https://news.ycombinator.com/ -------------------------------------------------------------------------------- /Web-Scraping/Songs_Lyrics/README.md: -------------------------------------------------------------------------------- 1 | # Songs lyrics scrapper 2 | 3 | ### This script takes input artist name and song name and gives the lyrics of the song by scrping from 'http://www.azlyrics.com/'. 4 | 5 | ##### Technolgies: 6 | 7 | - BeautifulSoup 8 | - requests 9 | 10 | ##### output: 11 | 12 | ![output](lyrics_op.png) 13 | 14 | 15 | -------------------------------------------------------------------------------- /Web-Scraping/Songs_Lyrics/lyrics_op.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Web-Scraping/Songs_Lyrics/lyrics_op.png -------------------------------------------------------------------------------- /Web-Scraping/Songs_Lyrics/song_lyrics.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | 4 | 5 | def get_lyrics(artist, song): 6 | base_url = 'http://www.azlyrics.com/' 7 | song_url = 'http://www.azlyrics.com/lyrics/' + artist + '/' + song + '.html' 8 | 9 | # Use requests library to get html from artist's page 10 | response = requests.get(song_url) 11 | 12 | # Make the html soup object 13 | soup = BeautifulSoup(response.content, 'html.parser') 14 | try: 15 | lyrics = soup.find('div' , class_ = 'col-xs-12 col-lg-8 text-center').find_all('div')[5].text 16 | print(lyrics) 17 | except AttributeError: 18 | print("Either this song doesnt exist or make sure you have entered the correct spelling!!") 19 | 20 | 21 | artist = input("Enter the name of the artist/band ") 22 | song = input("Enter the name of the song ") 23 | get_lyrics(artist, song) 24 | -------------------------------------------------------------------------------- /Web-Scraping/Times_of_india/README.md: -------------------------------------------------------------------------------- 1 | ## Scraping Times of India 2 | 3 | Scraping times of india top headlines in four domains : Flash news, News in Bulletin, Entertainment, Latest news. 4 | using REquests and Beautiful Soup Modules. 5 | 6 | Link for Website - "http://timesofindia.indiatimes.com/" 7 | 8 | ![output](TOI.png) 9 | -------------------------------------------------------------------------------- /Web-Scraping/Times_of_india/TOI.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Web-Scraping/Times_of_india/TOI.png -------------------------------------------------------------------------------- /Web-Scraping/Times_of_india/Times_of_india.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import datetime 3 | from bs4 import BeautifulSoup 4 | 5 | url = "http://timesofindia.indiatimes.com/" 6 | 7 | # Use requests library to get html from TOI's page 8 | response = requests.get(url) 9 | # Make the html soup object 10 | soup = BeautifulSoup(response.content, 'html.parser') 11 | 12 | print("\t!!!** The Times of India **!!!") 13 | today = datetime.date.today() 14 | print(today.strftime('\tThe date %d, %b %Y')) 15 | 16 | # scrping times of India in four domains: 17 | print("\n\t\t**** Flash news ****") 18 | for div in soup.findAll('div', attrs={'id':'featuredstory'}): 19 | for a in div.findAll('a'): 20 | print(a.text) 21 | 22 | print("\n\t\t**** News in Bulletin ****") 23 | for div in soup.findAll('div', attrs={'class':'top-story'}): 24 | for a in div.findAll('li'): 25 | print (a.text) 26 | 27 | 28 | print("\n\t\t**** Entertainment ****\t") 29 | for div in soup.findAll('div', attrs={'class':'entrmnt-wdgt-outer'}): 30 | for a in div.findAll('li'): 31 | print(a.text) 32 | 33 | 34 | print("\n\t\t**** Latest News ****\t\n") 35 | for div in soup.findAll('div', attrs={'id':'lateststories'}): 36 | for a in div.findAll('li'): 37 | print(a.text) 38 | -------------------------------------------------------------------------------- /Web-Scraping/amazon_reviews_scraping/README.md: -------------------------------------------------------------------------------- 1 | ## USE: As a part of projects where you are required to do sentiment analysis on customer reviews data.
2 | 3 | Scrapy is a web crawling framework for a developer to write code to create, which defines how a particular site (or a group of websites) will be scrapped. 4 | 5 | ### Steps:
6 | 7 | 1) From the conda-forge, install scrapy:
8 | >> conda install -c conda-forge scrapy 9 | 10 | In case you want to install from system, use: 11 | >> pip install scrapy 12 | 13 | 2) Start a project:
14 | >> scrapy startproject amazon_reviews_scraping 15 | 16 | 3) A spider is a chunk of python code that determines how a web page will be scrapped, it's the main component that crwals the webpage and extracts contents from it.
17 | So copy your link from the product review you want to scrape, and run the following:
18 | >> scrapy genspider amazon_review 19 | 20 | 4) Now you'll need to define a scrapy parser, which I've already done in:
21 | amazon_reviews_scraping/spider/scraper.py 22 | 23 | 5) Run the following to store the result in a csv file titled "reviews.csv", or you may change the name as per your convenience!
24 | >> scrapy runspider amazon_reviews_scraping/amazon_reviews_scraping/spiders/amazon_reviews.py -o reviews.csv 25 | -------------------------------------------------------------------------------- /Web-Scraping/amazon_reviews_scraping/items.py: -------------------------------------------------------------------------------- 1 | import scrapy 2 | 3 | 4 | class AmazonReviewsScrapingItem(scrapy.Item): 5 | # define the fields for your item here like: 6 | # name = scrapy.Field() 7 | pass 8 | -------------------------------------------------------------------------------- /Web-Scraping/amazon_reviews_scraping/middlewares.py: -------------------------------------------------------------------------------- 1 | from scrapy import signals 2 | 3 | from itemadapter import is_item, ItemAdapter 4 | 5 | 6 | class AmazonReviewsScrapingSpiderMiddleware: 7 | 8 | @classmethod 9 | def from_crawler(cls, crawler): 10 | 11 | s = cls() 12 | crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) 13 | return s 14 | 15 | def process_spider_input(self, response, spider): 16 | 17 | return None 18 | 19 | def process_spider_output(self, response, result, spider): 20 | 21 | for i in result: 22 | yield i 23 | 24 | def process_spider_exception(self, response, exception, spider): 25 | 26 | pass 27 | 28 | def process_start_requests(self, start_requests, spider): 29 | 30 | for r in start_requests: 31 | yield r 32 | 33 | def spider_opened(self, spider): 34 | spider.logger.info('Spider opened: %s' % spider.name) 35 | 36 | 37 | class AmazonReviewsScrapingDownloaderMiddleware: 38 | 39 | @classmethod 40 | def from_crawler(cls, crawler): 41 | 42 | s = cls() 43 | crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) 44 | return s 45 | 46 | def process_request(self, request, spider): 47 | 48 | return None 49 | 50 | def process_response(self, request, response, spider): 51 | 52 | return response 53 | 54 | def process_exception(self, request, exception, spider): 55 | 56 | pass 57 | 58 | def spider_opened(self, spider): 59 | spider.logger.info('Spider opened: %s' % spider.name) 60 | -------------------------------------------------------------------------------- /Web-Scraping/amazon_reviews_scraping/pipelines.py: -------------------------------------------------------------------------------- 1 | 2 | from itemadapter import ItemAdapter 3 | 4 | 5 | class AmazonReviewsScrapingPipeline: 6 | def process_item(self, item, spider): 7 | return item 8 | -------------------------------------------------------------------------------- /Web-Scraping/amazon_reviews_scraping/settings.py: -------------------------------------------------------------------------------- 1 | BOT_NAME = 'amazon_reviews_scraping' 2 | 3 | SPIDER_MODULES = ['amazon_reviews_scraping.spiders'] 4 | NEWSPIDER_MODULE = 'amazon_reviews_scraping.spiders' 5 | 6 | ROBOTSTXT_OBEY = True 7 | -------------------------------------------------------------------------------- /Web-Scraping/amazon_reviews_scraping/spiders/__init__.py: -------------------------------------------------------------------------------- 1 | # This package will contain the spiders of your Scrapy project 2 | -------------------------------------------------------------------------------- /Web-Scraping/amazon_reviews_scraping/spiders/__pycache__/amazon_reviews.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/powerexploit/Awesome-Python-Scripts/cea9bc0f3c1bf3e0a4649f3835ac0eff179f4771/Web-Scraping/amazon_reviews_scraping/spiders/__pycache__/amazon_reviews.cpython-38.pyc -------------------------------------------------------------------------------- /Web-Scraping/amazon_reviews_scraping/spiders/scraper.py: -------------------------------------------------------------------------------- 1 | import scrapy 2 | 3 | class AmazonReviewsSpider(scrapy.Spider): 4 | 5 | name = 'amazon_reviews' 6 | 7 | allowed_domains = ['amazon.in'] 8 | 9 | myBaseUrl = "https://www.amazon.com/OnePlus-Interstellar-Unlocked-Android-Smartphone/product-reviews/B0872473BF/ref=cm_cr_dp_d_show_all_btm?ie=UTF8&reviewerType=all_reviews" 10 | start_urls=[] 11 | 12 | for i in range(1,121): 13 | start_urls.append(myBaseUrl+str(i)) 14 | 15 | def parse(self, response): 16 | data = response.css('#cm_cr-review_list') 17 | 18 | star_rating = data.css('.review-rating') 19 | 20 | comments = data.css('.review-text-content') 21 | count = 0 22 | 23 | for review in star_rating: 24 | yield{'stars': ''.join(review.xpath('.//text()').extract()), 25 | 'comment': ''.join(comments[count].xpath(".//text()").extract()) 26 | } 27 | count=count+1 28 | -------------------------------------------------------------------------------- /Web-Scraping/links extractor/README.md: -------------------------------------------------------------------------------- 1 | # Links extractor script 2 | Links extractor is a python script which helps in extracting all the links in a web page. 3 | It goes through all the content in html data and extract data from all anchor tags. 4 | 5 | ## Libraries used 6 | * urllib is a python library used to send request used to website to retrive html content 7 | 8 | * bs4 is used to extract data from html content 9 | 10 | * xlwt is a python library used to write data to excel sheet 11 | -------------------------------------------------------------------------------- /Web-Scraping/links extractor/links-extractor.py: -------------------------------------------------------------------------------- 1 | # Importing required libraries 2 | from urllib.request import Request, urlopen 3 | from bs4 import BeautifulSoup 4 | from xlwt import Workbook 5 | from datetime import datetime 6 | 7 | #Tacking URL input from user 8 | url=input("Enter site to get links\n") 9 | links=[] 10 | while(len(url)==0): 11 | url=input("Enter site to get links\n") 12 | try: 13 | # Sending request to server using Urllib 14 | req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) 15 | html_data = urlopen(req).read() 16 | 17 | #Beautyfying all data to html form 18 | soup=BeautifulSoup(html_data,'html.parser') 19 | 20 | #Retriving all anchor tags in html data 21 | tags=soup('a') 22 | 23 | #Adding all href attribute values to list 24 | for tag in tags: 25 | if tag.has_attr('href'): 26 | links.append(tag['href']) 27 | except: 28 | #Check if any errors 29 | print("Please check the URL properly") 30 | if(len(links)==0): 31 | print("No links to fetch") 32 | else: 33 | # Tackning workbook 34 | wb=Workbook() 35 | 36 | #Creaing sheet in workbook 37 | sheet1 = wb.add_sheet('Links') 38 | 39 | #adding all data in list to excel sheet 40 | for i in range(0,len(links)): 41 | sheet1.write(i,0,links[i]) 42 | 43 | #Getting date and time to create file 44 | data_time=datetime.now() 45 | current_time = str(data_time.strftime("%H-%M-%S")) 46 | 47 | #Adding time to file name and saving file locally 48 | wb.save('links for '+current_time+'.xls') 49 | print("Done writing data to excel sheet") -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman --------------------------------------------------------------------------------