python-hard-way/3exercises/ex23.py

24 rindas
1.2 KiB
Python

import sys
script, input_encoding, error = sys.argv
def main(language_file, encoding, errors): # Define "main" function.
line = language_file.readline() # Read 1 line.
if line: # If this is true (which it will be as long as it is not the end of the file)
print_line(line, encoding, errors) # Call print_line function
return main(language_file, encoding, errors) # Call this function, the if statement will keep it from being an infinite loop. An ingenious sort of "for loop".
def print_line(line, encoding, errors): # Define print line function, which does actual encoding of lanugages.
next_lang = line.strip() # Strip trailing \n
raw_bytes = next_lang.encode(encoding, errors=errors) # Encode language from languages.txt and ecode it into raw bytes. Pass encoding argument to encode()
cooked_string = raw_bytes.decode(encoding, errors=errors) # Decode from raw bytes to a string.
print(raw_bytes, "<==>", cooked_string) # Print raw bytes on the left side, strings on the right.
languages = open("languages.txt", encoding="utf-8") # Open languages file.
main(languages, input_encoding, error) # Run main function with current paramaters and kick-start the loop.