【问题标题】:How to split a string with multiple conditions in python?如何在python中拆分具有多个条件的字符串?
【发布时间】:2019-09-18 03:39:26
【问题描述】:

假设我有一个 pandas 系列 op= SU 3180 和(CMG 3200 或 SU 3210) 我想要这样的输出 ["SU", "3180"] ["CMG", "3200"] ["SU", "3210"]

我的代码如下所示:

if op.str.contains('None').item():
    print('No Prereq for this course :) ')

else: 
    string = list()
    if op.str.contains('or').item():
        string=op.str.split('or')
    if op.str.contains('and').item():
        string=op.str.split('and')

    for item in string:
        print("Pre-req number:",item)
        for i in item:
            res=i.split()
            print(res)

我得到的输出是这样的 ['SU', '3180'] ['(CMG', '3200', 'or', 'SU', '3210)']

如何修复我的代码?

【问题讨论】:

    标签: python string loops if-statement split


    【解决方案1】:

    Regex 可以提供一个简单的解决方案

    import re
    
    txt = "op= SU 3180 and (CMG 3200 or SU 3210) "
    

    创建模式:

    reg_exp  = re.compile("([a-zA-Z]{2,3})(\s+\d{4})")
    

    找到匹配项:

    re.findall(reg_exp, txt)
    

    返回:

    [('SU', '3180'), ('CMG', '3200'), ('SU', '3210')]

    为了构建你的正则表达式,我推荐regex101.com

    【讨论】:

      【解决方案2】:

      这是我的解决方案,用你的运算符和括号分割字符串并提取如下操作数

      import re
      
      s = "SU 3180 and (CMG 3200 or SU 3210)"
      
      tokens = re.split(r"and|or|\(|\)", s)
      
      extracts = [token.strip().split() for token in tokens if len(token.strip())>0]
      print(extracts)
      

      输出

      [['SU', '3180'], ['CMG', '3200'], ['SU', '3210']]

      【讨论】:

        【解决方案3】:

        这对我有用:

        >>> a = 'CMG 3200 or SU 3210'
        >>> parts = a.split('or')
        >>> parts
        ['CMG 3200 ', ' SU 3210']
        >>> broken_parts = [p.strip().split() for p in parts]
        >>> broken_parts
        [['CMG', '3200'], ['SU', '3210']]
        

        基本上,您只需要我发布的 sn-p 的第 2 行和第 5 行,其余的只是为了显示。

        【讨论】:

          【解决方案4】:

          x =list(filter(lambda x:x, map(lambda x:re.sub(r'[^A-Za-z0-9]', '', x), res)))

          print (x) 这将从输出中删除括号

          【讨论】:

            【解决方案5】:

            您似乎只需要一个简单的助手来摆脱“and”、“or”和括号:

            def replace_all(txt, old, new):
                for word in old:
                    txt = txt.replace(word, new)
                return txt
            
            r = replace_all(op, ["and", "or", "(", ")"], ",")   # 'SU 3180 , ,CMG 3200 , SU 3210,'
            

            那么你就可以使用split得到想要的结果了:

            print([part.split() for part in r.split(",") if part.strip()])
            

            【讨论】:

              【解决方案6】:

              给你。您可能想考虑原始字符串指定 AND 和 OR 是否重要,但您想要的输出并未反映该信息。

              myString = 'SU 3180 and (CMG 3200 or SU 3210)' 
              prereqs = list()
              
              ## Separating courses
              arr1 = myString.split('or')
              for i in arr1:
                for j in i.split('and'):
                  ## cleaning
                    j = j.replace('(', '')
                    j = j.replace(')', '')
                    j = j.strip()
                    ## Split into letter/codes
                    j= j.split(' ')
                    prereqs.append(j)
              
              print(prereqs)
              

              【讨论】:

                【解决方案7】:
                word="SU 3180 and (CMG 3200 or SU 3210) "
                st1=word.replace("(","",-1)
                st2=st1.replace(")","",-1)
                st3=st2.replace("and",",",-1)
                st4=st3.replace("or",",",-1)
                lst1=list(st4.split(","))
                res=[]
                d=""
                for i in lst1:
                    j=i.strip()
                    if d in j:
                    res.append(j.split(" "))
                print(res)
                

                试试这个!!!

                【讨论】:

                  【解决方案8】:

                  这个表情,

                  ([A-Z]+)\s+(\d+)
                  

                  可能只是工作。

                  Demo

                  测试

                  import re
                  
                  expression = r"([A-Z]+)\s+(\d+)"
                  string = "SU 3180 and (CMG 3200 or SU 3210)"
                  
                  print([list(i) for i in re.findall(expression, string)])
                  print(re.findall(expression, string))
                  

                  输出

                  [['SU', '3180'], ['CMG', '3200'], ['SU', '3210']]
                  [('SU', '3180'), ('CMG', '3200'), ('SU', '3210')]
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2012-05-10
                    • 2018-12-23
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2012-12-27
                    相关资源
                    最近更新 更多