更好的可维护方式来组合来自多个选项的字符串

时间:2016-07-28 12:06:20

标签: python python-2.7 dry

我有一个用户可以传递多个选项的场景。对于传入的每个选项,我将获取文本,然后最终合并来自多个选项的文本并返回单个字符串。以下是我今天接受的三种选择。代码已经看起来不可维护了,当我添加更多选项时,逻辑会变得更糟:

if (len(self.options.passedin.split(",")) > 0): #multiple options were passed in
  ops = self.options.passedin.split(",")
  for op in ops:
     if (op == "option1"):
         op1_text = get_text_for_option1()
     elif (op == "option2"):
         op2_text = get_text_for_option2()
     elif (op == "option3"):
         op3_text = get_text_for_option3()

   #all three were passed in
   if ("option1" in ops and "option2" in ops and "option3" in ops):
      op1_op2 = op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op2_text.split())
      op3_op1_op2 = op1_op2 + " " + ' '.join(w for w in op1_op2.split() if w not in op3_text.split())
      return op3_op1_op2
   #option1 and option2 were passed in
   elif ("option1" in ops and "option2" in ops and "option3" not in ops):
      return op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op2_text.split())
   #option1 and option3 were passed in
   elif ("option1" in ops and "option3" in ops and "option2" not in ops):
      return op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op3_text.split())
   #option2 and option3 were passed in
   elif ("option2" in ops and "option3" in ops and "option1" not in ops):
      return op2_text + " " + ' '.join(w for w in op2_text.split() if w not in op3_text.split())

无法合并方法get_text_for_option1 get_text_for_option2 get_text_for_option3

2 个答案:

答案 0 :(得分:2)

使用dict将您的选项名称映射到相应的函数,该函数返回选项文本,将它们连接在一起,然后获取唯一的单词,例如:

from collections import OrderedDict

options = {
    'option1': get_text_for_option1,
    'option2': get_text_for_option2,
    'option3': get_text_for_option3
}

input_text = 'option3,option1,option2'

all_text = ' '.join(options[opt]() for opt in input_text.split(','))
unique = ' '.join(OrderedDict.fromkeys(all_text.split()))

答案 1 :(得分:0)

if (len(self.options.passedin.split(",")) > 0): #multiple options were passed in
    ops = self.options.passedin.split(",")
    opts = {
        'op1': get_text_for_option1() if 'option1' in ops else ' '
        'op2': get_text_for_option2() if 'option2' in ops else ' '
        'op3': get_text_for_option3() if 'option3' in ops else ' '
    }
    return (opts['op1'] + opts['op2'] + opts['op3']).strip()