我想基于CLI的参数执行不同的方法。我的main.py
:
from option import Option
import argparse
parser = argparse.ArgumentParser()
parser.add_argument( "--word", "-w", help="Find score for word", type=str)
args = parser.parse_args()
option = Option()
option.score_from_word(args.word)
和Option.py
:
class Option():
SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
(4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]
global LETTER_SCORES
LETTER_SCORES = {letter: score for score, letters in SCRABBLES_SCORES
for letter in letters.split()}
def score_from_word(self,word):
score = 0
for w in word:
if w in LETTER_SCORES.keys():
score += LETTER_SCORES.get(w)
print(score)
def score_from_file(self):
file = [line.rstrip('\n') for line in open('dictionary.txt', "r")]
print(max(sum(LETTER_SCORES[c.upper()] for c in word) for word in file))
如果在命令行中输入:python -w KOT,则返回7并确定。但是如何添加另一个参数并取决于他选择其他方法来执行?
答案 0 :(得分:1)
只需添加另一个参数,然后通过测试args(Namespace
)属性来确定您是哪种情况。
from option import Option
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument( "--word", "-w", help="Find score for word", type=str)
group.add_argument( "--file", "-f", help="Find score for words in file", action='store_true')
args = parser.parse_args()
option = Option()
if args.word:
option.score_from_word(args.word)
elif args.file:
option.score_from_file()