首页 > 解决方案 > 从 Python 中一列的开头和结尾删除空格和标点符号(括号除外)

问题描述

给定一个小数据集如下:

df = pd.DataFrame({'text':[' a..b?!??', '%hgh&12','abc123(bj)!!!', '$$$1234(gz)']})
df

出去:

            text
0       a..b?!??
1        %hgh&12
2  abc123(bj)!!!
3    $$$1234(gz)

我需要从列的左侧和右侧删除空格、标点符号,英文和中文括号除外text

预期结果:

            text
0           a..b
1         hgh&12
2     abc123(bj)
3       1234(gz)

我怎么能在 Python 中做到这一点?

我的代码:

df['text'] = df['text'].str.replace('[^\w\s]','')

出去:

0          ab
1       hgh12
2    abc123bj
3      1234gz
Name: text, dtype: object

谢谢。

标签: python-3.xpandasstr-replace

解决方案


我认为您需要使用不带括号Series.str.strip的所有值,string.punctuation并且还添加了

df['text'] = df['text'].str.strip('!"#$%&*+,-./:;<=>?@[\]^_`{|}~ ' + "'")
print (df)
         text
0        a..b
1      hgh&12
2  abc123(bj)
3    1234(gz)

动态解决方案应该是:

import string
rem = ['(',')']
add = [' ']
a = set(list(string.punctuation) + add) - set(rem)
    
df['text'] = df['text'].str.strip(''.join(a))

推荐阅读