Created
June 17, 2015 11:43
-
-
Save hcs42/fc4dd83c504418826a28 to your computer and use it in GitHub Desktop.
print_erl_string: a script that reads a text, collects the numbers between 32 and 128, and prints the corresponding ASCII characters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# print_erl_string is a script that reads a text, collects the numbers between | |
# 32 and 128, and prints the corresponding ASCII characters. | |
# | |
# Example: | |
# | |
# $ cat myfile | |
# [0,116,104,105,115,32,105,115,32,97,32,116,101,120,116,32,116,104,97,116, | |
# 32,105,115,32,110,111,116,32,102,111,114,109,97,116,116,101,100,32,97, | |
# 115,32,97,32,115,116,114,105,110,103,32,98,101,99,97,117,115,101,32,111, | |
# 102,32,97,32,110,111,110,45,97,115,99,105,105,32,99,104,97,114,97,99, | |
# 116,101,114] | |
# | |
# $ print_erl_string myfile | |
# this is a text that is not formatted as a string because of a non-ascii | |
# character | |
# $ | |
# | |
# When no parameter is specified, the script reads text from the standard | |
# input: | |
# | |
# $ cat myfile | print_erl_string | |
# this is a text that is not formatted as a string because of a non-ascii | |
# character | |
# $ | |
import sys | |
def w(s): | |
sys.stdout.write(s) | |
sys.stdout.flush() | |
def print_num(num): | |
if num != 0: | |
if 32 <= num <= 127: | |
try: | |
w(chr(num)) | |
except: | |
pass | |
else: | |
w('_') | |
def print_erl_string_fd(f): | |
num = 0 | |
while True: | |
ch = f.read(1) | |
if ch == '': | |
break | |
o = ord(ch) | |
if 48 <= o <= 57: | |
num = num * 10 + (o - 48) | |
else: | |
print_num(num) | |
num = 0 | |
print_num(num) | |
if len(sys.argv) > 1: | |
with open(sys.argv[1]) as f: | |
print_erl_string_fd(f) | |
else: | |
print_erl_string_fd(sys.stdin) | |
w('\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment