【发布时间】:2020-04-25 11:24:48
【问题描述】:
我正在尝试删除除字母、数字和! ? . ; , @' 来自我的 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
Afterwars,我也尝试使用相同的正则表达式模式使用 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
removing newlines from messy strings in pandas dataframe cells?
https://stackabuse.com/using-regex-for-text-manipulation-in-python/
【问题讨论】:
-
“如何提问”的基本示例。示例数据框、您的尝试、预期输出和接近答案的链接。 +1
-
这仍然是一个不清楚的问题。如果用字母和数字表示
[A-Za-z0-9],您如何定义连字符和其他一些字符? -
我对其进行了编辑以指定其他字符的含义!并感谢@Erfan :)
标签: regex python-3.x string pandas text-mining