「Python uniq.py」の版間の差分
Moutaku3dayo (トーク | 投稿記録) (ページの作成:「<syntaxhighlight lang="python" line> import argparse import sys def uniq(count, input_file): """ Filter out adjacent duplicate lines from input and optionally count occurrences. :param count: If True, prefix lines by the number of occurrences. :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:…」) |
Moutaku3dayo (トーク | 投稿記録) 編集の要約なし |
||
62行目: | 62行目: | ||
</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 uniq(count, input_file):
"""
Filter out adjacent duplicate lines from input and optionally count occurrences.
:param count: If True, prefix lines by the number of occurrences.
: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:
previous_line = None
count_occurrences = 0
for line in input_source:
line = line.rstrip() # Remove trailing newline characters
if line == previous_line:
count_occurrences += 1
else:
if previous_line is not None:
if count:
print(f"{count_occurrences} {previous_line}")
else:
print(previous_line)
previous_line = line
count_occurrences = 1
# Handle the last line
if previous_line is not None:
if count:
print(f"{count_occurrences} {previous_line}")
else:
print(previous_line)
finally:
if input_file:
input_source.close()
def main():
parser = argparse.ArgumentParser(description="Python implementation of the uniq command.")
parser.add_argument("-c", "--count", action="store_true", help="Prefix lines by the number of occurrences.")
parser.add_argument("-i", "--input", help="Input file path (default: standard input).")
args = parser.parse_args()
uniq(count=args.count, input_file=args.input)
if __name__ == "__main__":
main()