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

better maintainable way to combine strings from multiple options

我有一个用户可以传入多个选项的场景。对于传入的每个选项,我将获取文本,然后最终合并来自多个选项的文本和 return 单个字符串。以下是我今天接受的三个选项的处理方式。代码已经看起来无法维护,随着我添加更多选项,逻辑会变得更糟:

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_option1get_text_for_option2get_text_for_option3无法组合。

使用 dict 将您的选项名称映射到 returns 选项文本的适当函数,将它们连接在一起,然后取唯一的词,例如:

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()))
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()