在python中替换分隔符和分隔符之前,请先存储它们的位置



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

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

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

'CG1402L02'

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

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

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

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

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

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

您只需遍历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

参见:

  • 字符串.asii_letters
  • 字符串数字

您可以使用

specials = []

在迭代内部:

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

要获得元组列表而不是字典:

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

您可以这样做,将您需要的任何其他分隔符添加到列表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命令来替换它们。

最新更新