繁体   English   中英

Python,在其他列表的元素上分割输入字符串,并从中删除数字

[英]Python, Split the input string on elements of other list and remove digits from it

我在此问题上遇到了一些麻烦,需要您的帮助。 我必须制作一个Python方法(mySplit(x)),该方法接受一个输入列表(该元素只有一个字符串),然后将该元素拆分为其他列表和数字元素。 我使用Python 3.6,所以这是一个示例:

l=['I am learning']
l1=['____-----This4ex5ample---aint___ea5sy;782']
banned=['-', '+' , ',', '#', '.', '!', '?', ':', '_', ' ', ';']

返回的列表应如下所示:

mySplit(l)=['I', 'am', 'learning']
mySplit(l1)=['This', 'ex', 'ample', 'aint', 'ea', 'sy']

我尝试了以下方法,但始终会卡住:

def mySplit(x):

    l=['-', '+' , ',', '#', '.', '!', '?', ':', '_', ';'] #Banned chars
    l2=[i for i in x if i not in l] #Removing chars from input list
    l2=",".join(l2)
    l3=[i for i in l2 if not i.isdigit()] #Removes all the digits
    l4=[i for i in l3 if i is not ',']
    l5=[",".join(l4)]
    l6=l5[0].split(' ')
    return l6

mySplit(l1)
mySplit(l)

收益:

['T,h,i,s,e,x,a,m,p,l,e,a,i,n,t,e,a,s,y']
['I,', ',a,m,', ',l,e,a,r,n,i,n,g']

使用re.split()完成此任务:

import re
w_list = [i for i in re.split(r'[^a-zA-Z]', 
          '____-----This4ex5ample---aint___ea5sy;782') if i ]

Out[12]: ['This', 'ex', 'ample', 'aint', 'ea', 'sy']

我将从string导入punctuation ,并按如下所示进行正则表达式处理。

l=['I am learning']
l1=['____-----This4ex5ample---aint___ea5sy;782']
import re
from string import punctuation
punctuation # to see the punctuation marks.

>>> '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

' '.join([re.sub('[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\d]',' ', w) for w in l]).split()

这是输出:

>>>   ['I', 'am', 'learning']

请注意标点符号末尾附有\\d ,以删除所有数字。

同样的,

' '.join([re.sub('[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\d]',' ', w) for w in l1]).split() 

产量

>>> ['This', 'ex', 'ample', 'aint', 'ea', 'sy']

您还可以如下修改功能:

def mySplit(x):

    banned = ['-', '+' , ',', '#', '.', '!', '?', ':', '_', ';'] + list('0123456789')#Banned chars
    return ''.join([word if not word in banned else ' ' for word in list(x[0]) ]).split()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM