目标是仅保留单词并删除任何非字母字符
我开始使用包含括号内的字符串的列
(Pdb) test['userTweets'].head()
0 [the SELU function to verify that the mean/variance is ~ 0/1...
1 [trump is really @#$#@%@#@$@#
2 [Yo Hillary! should have @*&(@#$@ Trump...
3 [When are we going to see those memos?????...
...
因为它们包含括号,但实际上并不是包含列表的列,而是按照以下方式删除括号。
test['userTweets'] = test['userTweets'].str.extract(r'\[(.*)\]')
然后我使用python正则表达式功能:
(Pdb) regex = re.compile('[^a-zA-Z]')
(Pdb) test['userTweets'] = test['userTweets'].str.replace(regex,'')
但我得到了*** TypeError: object of type '_sre.SRE_Pattern' has no len()
但正则表达式已成功构建:
(Pdb) regex
<_sre.SRE_Pattern object at 0x11159f6a8>
有没有更好的方法将regex函数应用于pandas string列来替换/删除任何非字母字符?
答案 0 :(得分:1)
import string
test['userTweets'] = "".join([c for c in test['userTweets'] if c in string.ascii_letters])
我做了类似于上面的事情。
您的代码可能看起来有所不同,但您会得到一般的想法。