Python sort.py

提供:onayami
2025年3月28日 (金) 21:27時点におけるMoutaku3dayo (トーク | 投稿記録)による版 (ページの作成:「 <syntaxhighlight lang="python" line> import argparse import sys def sort_file(numeric, reverse, unique, input_file): """ Sort lines from the input file or standard input. :param numeric: Sort numerically if True. :param reverse: Sort in reverse order if True. :param unique: Remove duplicate lines if True. :param input_file: Input file path or None for standard input. """ # Open the input file or use standard input input_source…」)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
import argparse
import sys

def sort_file(numeric, reverse, unique, input_file):
    """
    Sort lines from the input file or standard input.

    :param numeric: Sort numerically if True.
    :param reverse: Sort in reverse order if True.
    :param unique: Remove duplicate lines if True.
    :param input_file: Input file path or None for standard input.
    """
    # Open the input file or use standard input
    input_source = open(input_file, "r") if input_file else sys.stdin

    try:
        # Read all lines from the input source
        lines = input_source.readlines()

        # Remove duplicates if unique is specified
        if unique:
            lines = list(set(lines))

        # Sort the lines
        if numeric:
            try:
                lines.sort(key=lambda x: float(x.strip()), reverse=reverse)
            except ValueError:
                print("Error: Non-numeric value encountered in numeric sort.", file=sys.stderr)
                sys.exit(1)
        else:
            lines.sort(reverse=reverse)

        # Print the sorted lines
        for line in lines:
            print(line, end="")
    finally:
        if input_file:
            input_source.close()

def main():
    parser = argparse.ArgumentParser(description="Python implementation of the sort command.")
    parser.add_argument("-n", "--numeric", action="store_true", help="Sort numerically.")
    parser.add_argument("-r", "--reverse", action="store_true", help="Sort in reverse order.")
    parser.add_argument("-u", "--unique", action="store_true", help="Remove duplicate lines.")
    parser.add_argument("-i", "--input", help="Input file path (default: standard input).")

    args = parser.parse_args()

    sort_file(numeric=args.numeric, reverse=args.reverse, unique=args.unique, input_file=args.input)

if __name__ == "__main__":
    main()