我正试图用以下命令运行我的文件:
python3 file.py -p pony_counts num_words
我的argparse代码是:
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)
我的代码使用该命令运行,但是,else块运行,而不管该命令是否包含-p参数。非常感谢您的帮助,谢谢!
运行命令:
python3 file.py -p 10
相当于:
python3 file.py -p=10
在Bash中(假设您在Mac或Linux上(,空白被视为标志后的等号。因此,如果您想为-p
标志传递一个值,您需要将其结构更像:
python3 file.py -p <tfidf arg> <pony_counts> <num_words>
仅仅阅读您的代码,也许您希望-p
是一个真/假标志,而不是一个输入?如果是,则可以使用action='store_true'
或action='store_false'
。文档中指出了如何做到这一点。从文档中撕下一个例子:
>>> 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)