-
-
Save letroot/6d61b35083af3c991cf5b5cdb3201580 to your computer and use it in GitHub Desktop.
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
import argparse | |
COMMA = ',' | |
DASH = '-' | |
def split_fields(fields, delimiter): | |
if delimiter in fields: | |
start, end = fields.split(delimiter) | |
start = int(start or 0) | |
end = int(end or 0) | |
if not (start or end): | |
raise ValueError("fields are numbered from 1") | |
else: | |
raise SyntaxError("Hey, only commas and hyphens are allowed") | |
return start, end | |
def cut_text(args): | |
delim = args.d or None | |
file = args.file[0] | |
fields = args.f | |
file_lines = [line.strip().split(delim) for line in open(file).readlines()] | |
if delim and len(delim) > 1: | |
raise ValueError("the delimiter must be a single character") | |
if COMMA in fields: | |
start, end = split_fields(fields, COMMA) | |
print (file_lines) | |
for field in file_lines: | |
try: | |
print(field[start-1], field[end-1]) | |
except IndexError: | |
print() | |
elif DASH in fields: | |
start, end = split_fields(fields, DASH) | |
for field in file_lines: | |
try: | |
if not end: | |
print(delim.join(field[start-1:])) | |
elif not start: | |
print(delim.join(field[:end+1])) | |
else: | |
print(delim.join(field[start-1:end+1])) | |
except IndexError: | |
print() | |
def process_args(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-d") | |
parser.add_argument("-f", required=True) | |
parser.add_argument("file", nargs=1, type=str) | |
args = parser.parse_args() | |
return args | |
cut_text(process_args()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment