如何删除除字母,数字和!之外的所有内容! ? 。 ; ,@'在python pandas df中使用正则表达式?

问题描述 投票:0回答:1

我正在尝试删除除字母,数字和!之外的所有内容! ? 。 ; ,@'来自我的python pandas列文本。我已经阅读了有关该主题的其他一些问题,但仍然无法使我的工作正常。

这里是我在做什么的一个例子:

import pandas as pd
df = pd.DataFrame({'id':[1,2,3,4],
                  'text':['hey+ guys! wuzup',
                              'hello p3ople!What\'s up?',
                              'hey, how-  thing == do##n',
                              'my name is bond, james b0nd']}
                )

然后我们有下表:

id                         text
1              hey+ guys! wuzup
2      hello p3ople!What\'s up?
3     hey, how-  thing == do##n
4   my name is bond, james b0nd

现在,尝试删除除字母,数字和!之外的所有内容。 ? 。 ; ,@'

第一次尝试:

df.loc[:,'text'] = df['text'].str.replace(r"^(?!(([a-zA-z]|[\!\?\.\;\,\@\'\"]|\d))+)$",' ',regex=True)

输出

id                         text
1              hey+ guys! wuzup
2       hello p3ople!What's up?
3      hey, how- thing == do##n
4   my name is bond, james b0nd

第二次尝试

df.loc[:,'text'] = df['text'].str.replace(r"(?i)\b(?:(([a-zA-Z\!\?\.\;\,\@\'\"\:\d])))",' ',regex=True)

输出

id                         text
1                  ey+ uys uzup
2              ello 3ople hat p
3            ey ow- hing == o##
4          y ame s ond ames 0nd

第三次尝试

df.loc[:,'text'] = df['text'].str.replace(r'(?i)(?<!\w)(?:[a-zA-Z\!\?\.\;\,\@\'\"\:\d])',' ',regex=True)

输出

id                         text
1                 ey+ uys! uzup
2           ello 3ople! hat' p?
3           ey, ow- hing == o##
4         y ame s ond, ames 0nd

[战后,我还尝试使用相同的正则表达式模式使用re.sub()函数,但仍然无法获得预期的结果。得到如下预期结果:

id                         text
1               hey guys! wuzup
2       hello p3ople!What's up?
3          hey, how-  thing don
4   my name is bond, james b0nd

有人可以帮我吗?

我在该主题上看到的链接:

Is there a way to remove everything except characters, numbers and '-' from a string

How do check if a text column in my dataframe, contains a list of possible patterns, allowing mistyping?

removing newlines from messy strings in pandas dataframe cells?

https://stackabuse.com/using-regex-for-text-manipulation-in-python/

regex python-3.x string pandas text-mining
1个回答
2
投票

这是您要寻找的吗?

df.text.str.replace("(?i)[^0-9a-z!?.;,@' -]",'')
Out: 
0                hey guys! wuzup
1        hello p3ople!What's up?
2          hey, how-  thing  don
3    my name is bond, james b0nd
Name: text, dtype: object
© www.soinside.com 2019 - 2024. All rights reserved.