我正在尝试在我看到符号列表中的符号时分割字符串(这是一个非常大的列表)。现在我想知道的东西,作为一个新的python用户,有一个方法而不是split方法,我可以告诉它一旦看到symbolList的任何memeber就拆分了吗? 这是一个例子:
symbolList=[',' , '&' , '8' , '9' , '.']
words = ['ha,di' , 'dea&r']
for word in words :
for i in word :
if i in symbolList:
#a method which splits the string by the symbol
我想要和出去一样:
newWords=['ha' , 'di' , 'dea' ,'r']
答案 0 :(得分:1)
尝试使用rsplit
words = ['ha,di' , 'dea&r','1.2']
for i in words:
print re.split(',|&|8|9|\.', i)
#output
['ha', 'di']
['dea', 'r']
['1', '2']
非常大的列表
import re
symbolList=[',' , '&' , '8' , '9' , '.']
regex = '|'.join(map(re.escape, symbolList))
words = ['ha,di' , 'dea&r','1.2']
for i in words:
print re.split(regex, i)
答案 1 :(得分:0)
您可以将单词列表转换为字符串,然后使用公共分隔符,
替换所有分隔符,现在在,
symbolList=[',' , '&' , '8' , '9' , '.']
words = ['ha,di' , 'dea&r']
delimiter = symbolList[0] #Any symbol in symbolList
words_str = delimiter.join(words) #converting words to a string separated by delimiter
print words_str
for symbol in symbolList: #replace other symbols with delimiters
words_str = words_str.replace(symbol,delimiter)
print words_str
print words_str.split(delimiter)
<强>输出强>
ha,di,dea&r
ha,di,dea,r
['ha', 'di', 'dea', 'r']