#!/usr/bin/env python3 import sys import logging import re import argh logger = logging.getLogger(__name__) """ sort_by_max.py - A Unix-style Python module / script to sort lines based on the maximum number in each line. This script can be used as a module: from sort_by_max import sort_by_max """ def extract_numbers(line, float_only=False): """ Extract numbers from a line. Args: line (str): Input line. float_only (bool): If True, only match floating point numbers with a decimal point. Returns: list of float: List of extracted numbers. """ pattern = r'\b-?\d+\.\d+\b' if float_only else r'\b-?\d+\.?\d*\b' numbers = re.findall(pattern, line) return [float(num) for num in numbers] def max_number(line, float_only=False): """ Find the maximum number in a line. Args: line (str): Input line. float_only (bool): If True, only consider floating point numbers with a decimal point. Returns: float: Maximum number found, or negative infinity if no numbers found. """ numbers = extract_numbers(line, float_only) return max(numbers) if numbers else float('-inf') def sort_by_max(lines, float_only=False, reverse=False): """ Sort lines based on the maximum number in each line. Args: lines (list of str): List of input lines to be sorted. float_only (bool): If True, only consider floating point numbers with a decimal point. reverse (bool): If True, sort in descending order. Returns: list of str: Sorted list of lines. """ return sorted(lines, key=lambda line: max_number(line, float_only), reverse=reverse) @argh.arg('-f', '--float', help='only match floating point numbers with a decimal point') @argh.arg('-r', '--reverse', help='sort in descending order') @argh.arg('--debug', help='enable debug logging') @argh.arg('--verbose', help='enable verbose logging') def main(float=False, reverse=False, debug=False, verbose=False): """ sort_by_max.py - A Unix-style Python module / script to sort lines based on the maximum number in each line. This script reads lines from stdin and writes the sorted output to stdout. Usage: cat input.txt | python3 sort_by_max.py [-f] [-r] [--debug] [--verbose] """ if debug: logging.getLogger().setLevel(logging.DEBUG) elif verbose: logging.getLogger().setLevel(logging.INFO) else: logging.getLogger().setLevel(logging.WARNING) input_lines = sys.stdin.readlines() sorted_lines = sort_by_max(input_lines, float_only=float, reverse=reverse) for line in sorted_lines: sys.stdout.write(line) if __name__ == '__main__': try: argh.dispatch_command(main) except Exception as e: logger.error(f"Error: %s %s", type(e).__name__, str(e)) sys.exit(1)