【问题标题】:Store delimiter and delimiter positions before replacing them in python在 python 中替换它们之前存储分隔符和分隔符位置
【发布时间】:2018-11-30 21:23:03
【问题描述】:

我正在处理文本模式问题。我有以下输入 -

term = 'CG-14/0,2-L-0_2'

我需要从输入项中删除所有可能的标点符号(分隔符)。基本上我需要输入项的以下输出 -

'CG1402L02'

在删除分隔符之前,我还需要存储(以任何格式(对象、字典、元组等))分隔符和分隔符的位置。

输出示例(如果作为元组返回) -

((-,2), (/,5), (,,7), (-,9), (-,11), (_,13))

我可以使用以下 python 代码获得输出 -

re.sub(r'[^\w]', '', term.replace('_', ''))

但是在删除分隔符之前如何存储分隔符和分隔符位置(以最有效的方式)?

【问题讨论】:

    标签: python python-3.x delimiter


    【解决方案1】:

    您只需穿过term 并在途中收集所有必需信息:

    from string import ascii_letters,digits
    
    term = 'CG-14/0,2-L-0_2'
    
    # defined set of allowed characters a-zA-Z0-9
    # set lookup is O(1) - fast
    ok = set(digits +ascii_letters)  
    
    specials = {}
    clean = []
    for i,c in enumerate(term):
        if c in ok:
            clean.append(c)
        else:
            specials.setdefault(c,[])
            specials[c].append(i)
    
    cleaned = ''.join(clean)
    
    print(clean)
    print(cleaned)
    print(specials)
    

    输出:

    ['C', 'G', '1', '4', '0', '2', 'L', '0', '2']     # list of characters in set ok 
    CG1402L02                                         # the ''.join()ed list 
    
    {'-': [2, 9, 11], '/': [5], ',': [7], '_': [13]}  # dict of characters/positions not in ok
    

    见:


    你可以使用

    specials = []
    

    在迭代内部:

    else:
        specials.append((c,i)) 
    

    获取元组列表而不是字典:

    [('-', 2), ('/', 5), (',', 7), ('-', 9), ('-', 11), ('_', 13)]
    

    【讨论】:

      【解决方案2】:

      您可以这样做,将您需要的任何其他分隔符添加到列表delims

      term = 'CG-14/0,2-L-0_2'   
      delims = ['-','/',',','_']
      locations = []
      pos = 0
      for c in term: ##iterate through the characters in the string
          if c in delims:
              locations.append([c,pos]) ##store the character and its original position 
          pos+=1
      

      然后你用re.sub命令来替换它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-17
        • 1970-01-01
        • 2017-03-17
        • 2017-01-22
        • 2021-11-10
        • 1970-01-01
        相关资源
        最近更新 更多