Found 33676 Articles for Programming

How to Visualize API results with Python

Kiran P
Updated on 10-Nov-2020 05:45:39

1K+ Views

Introduction..One of the biggest advantage of writing an API is to extract current/live data, even when the data is rapidly changing, an API will always get up to date data. API programs will use very specific URLs to request certain information e.g. Topp 100 most played songs of 2020 in Spotify or Youtube Music. The requested data will be returned in an easily processed format, such as JSON or CSV.Python allows the user to write API calls to almost any URL you can think of. In this example I will show how to extract API results from GitHub and visualize ... Read More

How to implement Multithreaded queue With Python

Kiran P
Updated on 10-Nov-2020 05:39:02

3K+ Views

Introduction..In this example, we will create a task queue that holds all the tasks to be executed and a thread pool that interacts with the queue to process its elements individually.We will begin with the question, what is a Queue?. A queue is a data structure that is a collection of different elements maintained in a very specific order. Let me explain by taking a real life example.Assume you stand in line to pay your grocery billat a grocery shop counter, (don't ask me which grocery shop)In a line of people waiting to pay their bills, you will notice the ... Read More

How to scan for a string in multiple document formats (CSV, Text, MS Word) with Python?

Kiran P
Updated on 10-Nov-2020 05:36:10

823 Views

Problem..Assume you have a directory full of files with different formats, to search for a particular keyword.Getting ready..Install below packages.1. beautifulsoup42. python-docxHow to do it...1. Write a function to search for a string in CSV format. I will be using csv.reader module to go through the file and search for the string and return True when found else False.Exampledef csv_stringsearch(input_file, input_string): """ Function: search a string in csv files. args: input file , input string """ with open(input_file) as file: for row in csv.reader(file): for column in row: if input_string in column.lower(): return True return False2. Function to search a ... Read More

How to make the argument optional in Python

Kiran P
Updated on 10-Nov-2020 05:32:52

367 Views

Introduction..Sometimes, the programs require optional arguments when supplied will use them else go back to default declarations. We will see in this example on how to use them.The parameters that start with dashes (--) are identified as optional, so they can be left out, and they may have default values.Parameters that don’t start with dashes are positional and are usually required, so they do not have default values.How to do it...Exampleimport argparse parser = argparse.ArgumentParser(description='Optional Argument Example') parser.add_argument('-n', '--name', metavar='name', default='World', help='Say Hello to ') args = parser.parse_args() print(f"Hello {args.name}")The “metavar” will show up in the usage to describe the ... Read More

How to combine multiple graphs in Python

Kiran P
Updated on 10-Nov-2020 05:28:29

19K+ Views

IntroductionMatplotlib allows to add more than one plot in the same graph. In this tutorial, I will show you how to present data in the same plot, on two different axes.How to do it..1. Install matplotlib by opening up the python command prompt and firing pip install matplotlib.import matplotlib.pyplot as plt2. Prepare the data to be displayed.import matplotlib.pyplot as plt # data prep (I made up data no accuracy in these stats) mobile = ['Iphone', 'Galaxy', 'Pixel'] # Data for the mobile units sold for 4 Quaters in Million units_sold = (('2016', 12, 8, 6), ('2017', 14, 10, ... Read More

How to match text at the start or end of a string in Python?

Kiran P
Updated on 10-Nov-2020 05:24:29

949 Views

Problem..Assume you need to check the start or end of a string for a specific text patterns. The common patterns might be filename extensions but can also be anything. I will show you few methods on how you can do this.Startswith() methodA simple way to check the beginning of a string is by using startswith() method.Exampletext = "Is USA colder than Australia?" print(f"output {text.startswith('Is')}")OutputTrueExamplefilename = "Hello_world.txt" print(f"output {filename.startswith('Hello')}")OutputTrueExamplesite_url = 'https://www.something.com' print(f"output {site_url.startswith('http:')}")OutputFalseExampleprint(f"output {site_url.startswith('https:')}")OutputTrueendswith() Method.A simple way to check the ending of a string is by using endswith() method.Outputtext = "Is USA colder than Australia?" print(f"output ... Read More

How to Search and Replace text in Python?

Kiran P
Updated on 10-Nov-2020 05:22:42

706 Views

ProblemYou want to search for and replace a text pattern in a string.If we have a very simple literal patterns, using the str.replace() method is an optimal solution.Exampledef sample(): yield 'Is' yield 'USA' yield 'Colder' yield 'Than' yield 'Canada?' text = ' '.join(sample()) print(f"Output {text}")OutputIs USA Colder Than Canada?Let us first see how to search a text.# search for exact text print(f"Output {text == 'USA'}")OutputFalseWe can search for the text using the basic string methods, such as str.find(), str.endswith(), str.startswith().# text start with print(f"Output {text.startswith('Is')}")OutputTrue# text ends with print(f"Output {text.startswith('Is')}")OutputTrue# search text with find print(f"Output ... Read More

How to Implement Priority Queue in Python?

Kiran P
Updated on 10-Nov-2020 05:20:13

514 Views

Introduction...The queue module provides a first-in, first-out (FIFO), Last-in, First out (LIFO) data structure suitable for multi-threaded programming. Queues can be used to pass data or any wide range of information e.g. session details, paths, variables, .. between creator and consumer threads safely. Locking is generally handled for the caller.Note : This discussion assumes you already understand the general nature of a queue. If you do not, you may want to read some of the references before continuing.1. Let us implement a basic FIFO Queue.import queue fifo = queue.Queue() # put numbers into queue for i in range(5): fifo.put(i) ... Read More

How to improve file reading performance in Python with MMAP function?

Kiran P
Updated on 09-Nov-2020 11:02:12

773 Views

Introduction..MMAP abbreviated as memory mapping when mapped to a file uses the operating systems virtual memory to access the data on the file system directly, instead of accessing the data with the normal I/O functions. There by improving the I/O performance as it does not require either making a separate system call for each access or copying data between buffers.To a matter of fact anything in memory for instance a SQLlite database when created in-memeory has better performance compared to on disk.Memory-mapped files can be treated as mutable strings or file-like objects, depending on what you want to do.MMAP supports ... Read More

How to read text files using LINECACHE in Python

Kiran P
Updated on 09-Nov-2020 10:59:40

583 Views

Solution..The linecache module implements cache which holds the contents of files, parsed into separate lines, in memory. linecache module returns line/s by indexing into a list, and saves time over repeatedly reading the file and parsing lines to find the one desired.lincecache module is very useful when looking for multiple lines from the same file.Prepare test data. You can get this text by just using Google and searching for sample text.Lorem ipsum dolor sit amet, causae apeirian ea his, duo cu congue prodesset. Ut epicuri invenire duo, novum ridens eu has, in natum meliore noluisse sea. Has ei stet explicari. ... Read More

Advertisements