Extract Information From Parameters

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to extract numbers from a given text, calculate the average of those numbers, and round the result to two decimal places. This project will help you practice working with regular expressions and handling command-line arguments in Python.

👀 Preview

$ python3 ~/project/find_num.py "a11 b3.14c15 16"
11.29
$ python3 ~/project/find_num.py "a 5 b 6 c7 dd8 9"
7.00
$ python3 ~/project/find_num.py "ad1dg6dgd9dg4qwe10"
6.00

🎯 Tasks

In this project, you will learn:

  • How to use regular expressions to find all the numbers (both integers and floating-point numbers) in a given text
  • How to convert the matched numbers from strings to floats
  • How to calculate the average of the extracted numbers
  • How to format the average result to two decimal places
  • How to handle command-line arguments in a Python script

🏆 Achievements

After completing this project, you will be able to:

  • Write a Python script that can extract numbers from a given text
  • Calculate the average of the extracted numbers
  • Format the average result to two decimal places
  • Run the script from the command line and pass the text as an argument

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/AdvancedTopicsGroup(["`Advanced Topics`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/AdvancedTopicsGroup -.-> python/regular_expressions("`Regular Expressions`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/PythonStandardLibraryGroup -.-> python/os_system("`Operating System and System`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-302721{{"`Extract Information From Parameters`"}} python/with_statement -.-> lab-302721{{"`Extract Information From Parameters`"}} python/variables_data_types -.-> lab-302721{{"`Extract Information From Parameters`"}} python/numeric_types -.-> lab-302721{{"`Extract Information From Parameters`"}} python/type_conversion -.-> lab-302721{{"`Extract Information From Parameters`"}} python/conditional_statements -.-> lab-302721{{"`Extract Information From Parameters`"}} python/for_loops -.-> lab-302721{{"`Extract Information From Parameters`"}} python/list_comprehensions -.-> lab-302721{{"`Extract Information From Parameters`"}} python/lists -.-> lab-302721{{"`Extract Information From Parameters`"}} python/tuples -.-> lab-302721{{"`Extract Information From Parameters`"}} python/dictionaries -.-> lab-302721{{"`Extract Information From Parameters`"}} python/function_definition -.-> lab-302721{{"`Extract Information From Parameters`"}} python/importing_modules -.-> lab-302721{{"`Extract Information From Parameters`"}} python/standard_libraries -.-> lab-302721{{"`Extract Information From Parameters`"}} python/regular_expressions -.-> lab-302721{{"`Extract Information From Parameters`"}} python/data_collections -.-> lab-302721{{"`Extract Information From Parameters`"}} python/os_system -.-> lab-302721{{"`Extract Information From Parameters`"}} python/build_in_functions -.-> lab-302721{{"`Extract Information From Parameters`"}} end

Set Up the Project Environment

In this step, you will learn how to set up the project environment and create the necessary files.

  1. Open a terminal and navigate to the /home/labex/project directory.
  2. Create a new Python file named find_num.py in the /home/labex/project directory.
cd /home/labex/project
touch find_num.py
  1. Open the find_num.py file in a text editor.

Import the Required Modules

In this step, you will learn how to import the necessary modules for the project.

  1. Add the following code at the beginning of the find_num.py file:
import re  ## Import the regular expressions module
import sys  ## Import the sys module for command-line arguments

These modules will be used to work with regular expressions and handle command-line arguments.

Define the Calculate Average Function

In this step, you will learn how to define a function to calculate the average of numbers in a given text.

  1. Add the following function to the find_num.py file:
def calculate_average(text):
    ## Use a regular expression pattern to find all floating-point and integer numbers in the text
    numbers = re.findall(r"[-+]?\d*\.\d+|\d+", text)
    ## Convert the matched numbers from strings to floats using list comprehension
    numbers = [float(num) for num in numbers]
    ## Calculate the average of these numbers
    average = sum(numbers) / len(numbers)
    ## Format the average with two decimal places
    average_formatted = "{:.2f}".format(average)
    return average_formatted

This function takes a text as input, uses a regular expression to extract all the numbers (both integers and floating-point numbers) from the text, calculates the average of these numbers, and formats the result to two decimal places.

Implement the Main Logic

In this step, you will learn how to implement the main logic of the script.

  1. Add the following code to the find_num.py file:
if __name__ == "__main__":
    ## Read the text to be analyzed from the command-line arguments (the first argument, sys.argv[1])
    text = sys.argv[1]
    ## Call the calculate_average function with the provided text
    average = calculate_average(text)
    ## Print the calculated average with two decimal places
    print(average)

This code checks if the script is being run as the main program (if __name__ == "__main__":). If so, it reads the text to be analyzed from the command-line arguments (the first argument, sys.argv[1]), calls the calculate_average function with the provided text, and prints the calculated average.

Test the Script

In this step, you will learn how to test the script with the provided examples.

  1. Save the find_num.py file.
  2. Run the script with the provided examples:
python3 /home/labex/project/find_num.py "a11 b3.14c15 16"
python3 /home/labex/project/find_num.py "a 5 b 6 c7 dd8 9"
python3 /home/labex/project/find_num.py "ad1dg6dgd9dg4qwe10"

The output should match the expected results:

11.29
7.00
6.00

Congratulations! You have completed the project. The script you have created can now extract numbers from a given text, calculate the average, and round the result to two decimal places.

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like