杰瑞科技汇

python converter

Of course! The term "converter" in Python is very broad. It can refer to a simple utility function, a full-fledged command-line tool, or a library for converting between data formats.

python converter-图1
(图片来源网络,侵删)

Let's break down the most common types of "converters" with clear examples.


The Simple Utility Function

This is the most basic form. A function that takes one type of input and returns another. A classic example is converting a temperature from Celsius to Fahrenheit.

Example: Temperature Converter

Here's a function that converts Celsius to Fahrenheit.

def celsius_to_fahrenheit(celsius):
  """
  Converts a temperature from Celsius to Fahrenheit.
  Args:
    celsius (float or int): The temperature in Celsius.
  Returns:
    float: The temperature in Fahrenheit.
  """
  fahrenheit = (celsius * 9/5) + 32
  return fahrenheit
# --- How to use it ---
temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C is equal to {temp_f}°F")
# Output: 25°C is equal to 77.0°F

You can easily extend this to a more general converter that takes the unit as an argument.

python converter-图2
(图片来源网络,侵删)

Example: General Unit Converter

def convert_temperature(value, from_unit, to_unit):
  """
  Converts a temperature between Celsius, Fahrenheit, and Kelvin.
  Args:
    value (float or int): The temperature value.
    from_unit (str): The source unit ('C', 'F', 'K').
    to_unit (str): The target unit ('C', 'F', 'K').
  Returns:
    float: The converted temperature.
  """
  # First, convert the input value to Celsius (the base unit)
  if from_unit == 'C':
    celsius = value
  elif from_unit == 'F':
    celsius = (value - 32) * 5/9
  elif from_unit == 'K':
    celsius = value - 273.15
  else:
    raise ValueError("Invalid 'from_unit'. Use 'C', 'F', or 'K'.")
  # Then, convert from Celsius to the target unit
  if to_unit == 'C':
    return celsius
  elif to_unit == 'F':
    return (celsius * 9/5) + 32
  elif to_unit == 'K':
    return celsius + 273.15
  else:
    raise ValueError("Invalid 'to_unit'. Use 'C', 'F', or 'K'.")
# --- How to use it ---
print(f"100°F to Celsius: {convert_temperature(100, 'F', 'C'):.2f}")
# Output: 100°F to Celsius: 37.78
print(f"0°C to Kelvin: {convert_temperature(0, 'C', 'K')}")
# Output: 0°C to Kelvin: 273.15
print(f"300K to Fahrenheit: {convert_temperature(300, 'K', 'F'):.2f}")
# Output: 300K to Fahrenheit: 80.33

The Command-Line Interface (CLI) Converter

A more advanced and useful converter is one you can run from your terminal. We'll use Python's built-in argparse module to create a tool that accepts arguments from the command line.

Let's create a file named temp_cli.py and put our converter logic in it.

Example: temp_cli.py

import argparse
def convert_temperature(value, from_unit, to_unit):
  """The same conversion logic as before."""
  if from_unit == 'C':
    celsius = value
  elif from_unit == 'F':
    celsius = (value - 32) * 5/9
  elif from_unit == 'K':
    celsius = value - 273.15
  else:
    raise ValueError(f"Invalid 'from_unit': {from_unit}")
  if to_unit == 'C':
    return celsius
  elif to_unit == 'F':
    return (celsius * 9/5) + 32
  elif to_unit == 'K':
    return celsius + 273.15
  else:
    raise ValueError(f"Invalid 'to_unit': {to_unit}")
def main():
  """Main function to handle command-line arguments."""
  parser = argparse.ArgumentParser(
    description="A command-line tool to convert temperatures."
  )
  # Add the arguments
  parser.add_argument("value", type=float, help="The temperature value to convert.")
  parser.add_argument("from_unit", choices=['C', 'F', 'K'], help="The source unit (C, F, or K).")
  parser.add_argument("to_unit", choices=['C', 'F', 'K'], help="The target unit (C, F, or K).")
  # Parse the arguments
  args = parser.parse_args()
  try:
    # Perform the conversion
    result = convert_temperature(args.value, args.from_unit, args.to_unit)
    # Print the result in a clean format
    print(f"{args.value}°{args.from_unit} is equal to {result:.2f}°{args.to_unit}")
  except ValueError as e:
    print(f"Error: {e}")
if __name__ == "__main__":
  main()

How to Run the CLI Converter

  1. Save the code above as temp_cli.py.
  2. Open your terminal or command prompt.
  3. Run the script with the required arguments.
# Convert 100 degrees Fahrenheit to Celsius
python temp_cli.py 100 F C
# Output: 100.0°F is equal to 37.78°C
# Convert 0 degrees Celsius to Kelvin
python temp_cli.py 0 C K
# Output: 0.0°C is equal to 273.15K
# Get help
python temp_cli.py -h
# Output:
# usage: temp_cli.py [-h] value from_unit to_unit
#
# A command-line tool to convert temperatures.
#
# positional arguments:
#   value        The temperature value to convert.
#   from_unit    The source unit (C, F, or K).
#   to_unit      The target unit (C, F, or K).
#
# options:
#   -h, --help   show this help message and exit

The Data Format Converter

Another very common type of converter changes the format of data, for example, from a Python dictionary to a JSON string, or from a CSV file to a list of dictionaries.

Example: Dictionary to JSON Converter

Python's built-in json module is perfect for this.

python converter-图3
(图片来源网络,侵删)
import json
def convert_dict_to_json(data_dict, indent=None):
  """
  Converts a Python dictionary to a JSON formatted string.
  Args:
    data_dict (dict): The Python dictionary to convert.
    indent (int, optional): Number of spaces for indentation. Defaults to None.
  Returns:
    str: A JSON formatted string.
  """
  try:
    json_string = json.dumps(data_dict, indent=indent)
    return json_string
  except TypeError as e:
    print(f"Error converting to JSON: {e}")
    return None
# --- How to use it ---
user_data = {
  "name": "Alice",
  "age": 30,
  "is_student": False,
  "courses": ["History", "Math"]
}
# Convert with pretty-printing (indentation)
json_output = convert_dict_to_json(user_data, indent=2)
print(json_output)

Output:

{
  "name": "Alice",
  "age": 30,
  "is_student": false,
  "courses": [
    "History",
    "Math"
  ]
}

For the reverse (JSON to dictionary), you use json.loads().

json_string = '{"name": "Bob", "age": 25}'
python_dict = json.loads(json_string)
print(python_dict)
print(type(python_dict))
# Output: {'name': 'Bob', 'age': 25}
# Output: <class 'dict'>

Summary

Type of Converter What it Does Key Python Tools/Concepts Example Use Case
Utility Function Takes input, returns converted output. def, return, type hints. A simple math or unit conversion inside a larger program.
CLI Tool Runs from the terminal, accepts arguments. argparse, if __name__ == "__main__". A standalone script for users to run from their command line.
Data Format Converter Changes data structure or serialization format. json, csv, pandas, xml.etree.ElementTree. Converting between JSON, CSV, XML, or database formats.

To give you the best answer, could you tell me what kind of data or format you want to convert? For example:

  • "I want to convert feet to meters."
  • "I want to convert a CSV file to an Excel file."
  • "I want to convert a list of numbers into a histogram."
分享:
扫描分享到社交APP
上一篇
下一篇