קורס Python 3 שיעור קבוצות


זה נושא דיון מלווה לערך המקורי ב- https://www.tocode.co.il/bundles/python/lessons/15-sets

קוד עם אפשרות להתעלם מאותיות גדולות/קטנות ולקבל שם קובץ אחר, כתלות בארגומנטים המגעים משרת הפקודה בעזרת ספריית argparse:

import fileinput
import argparse

parser = argparse.ArgumentParser(description='Count unique words from a file.')
parser.add_argument('--file', '-f', default='story.txt')
parser.add_argument('--case-insensitive', '-c', action='store_true', dest='casefold')
args = parser.parse_args()

unique_words = set()
overall_words = 0
try:
    for line in fileinput.input(args.file):
        if args.casefold:
            line = line.casefold()
        words = line.split()
        unique_words.update(words)
        print(f'[num of words: {len(words)}]: ', words)
        overall_words += len(words)
except FileNotFoundError as e:
    print(f'Failed to read from file -', e, '\nAborting.')
    exit(1)

print(f'Number of unique_words: {len(unique_words)}')
print(f'Number of overall_words: {overall_words}')

פלט דוגמה:

λ py count_with_sets.py -c -f=bla.txt
[num of words: 2]:  ['one', 'line']
[num of words: 5]:  ['is', 'deffernt', 'than', 'the', 'other']
[num of words: 5]:  ['one', 'line', 'is', 'the', 'same']
[num of words: 3]:  ['one', 'of', 'us']
[num of words: 3]:  ['is', 'it', 'true?']
[num of words: 6]:  ['can', 'he', 'be', 'the', 'kwisatz', 'haderach?']
Number of unique_words: 17
Number of overall_words: 24
לייק 1

הי,

הפקודה exit לא מומלצת ב Python. הדרך המקובלת לצאת מתוכנית באמצע היא sys.exit לדוגמא:

import sys

sys.exit('Failed to read from file')
לייק 1

תודה.
האם הפלט מהפקודה הזו מגיע ל-stdout ואפשר לסמוך על זה שכום יראו את ההודעה? או ל-stderr ואז אולי כדאי להשאיר גם את ה-print?

מגיע ל stderr - לדעתי זו התנהגות עדיפה כי היא מסתדרת טוב עם redirection (אפשר לשמור רק את השגיאות לקובץ וכו)

לייק 1

היי @ynonp, עכשיו כשהחג מאחורנו אשמח לקבל ממך משוב על התרגיל מעבר לשימוש ב-exit.
תודה :smiley:

חוץ מה exit נראה אחלה