正则表达式不将匹配项重新编码为Tru

2024-06-07 11:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含文本数据的数据框,我正在尝试清除包含空内容值的行。我有一行的内容列如下所示:

articles.loc[197040, 'content']
'     '

我试过用.isnull()清理它,但它不能识别空字符串。所以我求助于正则表达式并尝试:

nothing = re.compile(r'\W{1,}')
articles = articles[articles['content'] != nothing]

但这就留下了空的文章。如果我尝试:

'     ' == nothing

我得到False。但是regex tester似乎表明这应该是可行的。使用r'\W*'也会返回False。你知道吗

当尝试其他正则表达式组合时,其他无意义字符串(例如逗号和空格的混合)的问题仍然存在。你知道吗

谢谢你的帮助。你知道吗

编辑:

这里也不承认等价性:

'what.' == re.compile(r'\w*\.')
False

或者在这里:

'6:45' == r'[^A-Z]{1,}'
False

以此类推。你知道吗


Tags: 数据字符串文本refalse内容文章content
2条回答

要检查正则表达式是否与字符串匹配,必须使用match方法,而不是检查是否相等。你基本上是在比较一个字符串和一个模式对象,当然,它们并不相等。试试这个:

nothing.match('    ') # out: <_sre.SRE_Match object; span=(0, 4), match='    '>
x.match(' , , ,') # out: <_sre.SRE_Match object; span=(0, 6), match=' , , ,'>

您可以使用^{}内置解决此问题,如果字符串中只有空格字符且至少有一个字符,则返回true。你知道吗


演示,同时过滤空字符串:

import pandas as pd
articles =  pd.DataFrame({'content' : ['foo','bar','   ','foo','    ','']})    
articles = articles[(~articles['content'].str.isspace()) & (articles['content'] != '')]

>>> articles
  content
0     foo
1     bar
3     foo

相关问题 更多 >

    热门问题