「Python sort.py」の版間の差分

提供:onayami
(ページの作成:「 <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…」)
 
編集の要約なし
 
57行目: 57行目:


</syntaxhighlight>
</syntaxhighlight>
== 関連項目 ==
* [[Python cat.py]]
* [[Python cut.py]]
* [[Python sort.py]]
* [[Python uniq.py]]
* https://chatgpt.com/
[[Category:chatgpt]]
[[Category:Python]]

2025年3月28日 (金) 21:29時点における最新版

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()


関連項目