i’m trying to run my file with the following command:
python3 file.py -p pony_counts num_words
where my argparse code is:
parser = argparse.ArgumentParser() parser.add_argument('pony_counts', type=str, help="output file for compute_pony_lang.py") parser.add_argument('num_words', type=int, help="num of words we want in the output list for each speaker") parser.add_argument('-p', action='store_true') args = parser.parse_args() with open(args.pony_counts) as f: df = json.load(f) df = pd.DataFrame(df) # convert json to df df = df.drop([i for i in df.index if i.isalpha() == False]) # drop words that contain apostrophe total_words_per_pony = df.sum(axis=0) # find total no. of words per pony df.insert(6, "word_sum", df.sum(axis=1)) # word_sum = total occurrences of a word (e.g. said by all ponies), in the 7th column of df tf = df.loc[:,"twilight":"fluttershy"].div(total_words_per_pony.iloc[0:6]) # word x (said by pony y) / word x (total occurrences) ponies_tfidf = tfidf(df, tf) ponies_alt_tfidf = tfidf(df, tf) d = {} ponies = ['twilight', 'applejack', 'rarity', 'pinky', 'rainbow', 'fluttershy'] if args.p: for i in ponies: d[i] = ponies_alt_tfidf[i].nlargest(args.num_words).to_dict() else: # calculate tfidf according to the method presented in class for i in ponies: d[i] = ponies_tfidf[i].nlargest(args.num_words).to_dict() final = {} for pony, word_count in d.items(): final[pony] = list(word_count.keys()) pp = pprint.PrettyPrinter(indent = 2) pp.pprint(final)
my code runs with the command – however, the else block runs regardless of whether the command contains the -p argument or not. would really appreciate help, thanks!
Advertisement
Answer
Running the command:
python3 file.py -p 10
is equivalent to:
python3 file.py -p=10
In Bash (assuming you’re on a Mac or Linux) the whitespace is treated the same as an equal sign after a flag. So if you wanted to pass a value for the -p
flag you would need to structure it more like:
python3 file.py -p <tfidf arg> <pony_counts> <num_words>
Just reading your code, perhaps you want -p
to be a true / false flag instead of an input? If so you can use action='store_true'
or action='store_false'
. It’s pointed out how to do this in the docs. Ripping an example out of the documentation:
>>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', action='store_true') >>> parser.add_argument('--bar', action='store_false') >>> parser.add_argument('--baz', action='store_false') >>> parser.parse_args('--foo --bar'.split()) Namespace(foo=True, bar=False, baz=True)