python中的grepl函数

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

我想重新创建一个从R到Python的代码段。我有来自R(Python中的数据框)的小标题,它看起来像这样:

column1       column2                                 column3
amsterdam     het dag calamiteit bij doen gratis dag  2013
rotterdam     blijdorp groet gratis burp het ik ben   2015

使用下面的这段代码,我试图将描述提取为单个字符串。这是代码:

#R code
for (i in 1:nrow(tibble)) {
    des <- pull(tibble[i,2])
}

#Python code
for i in df:    
    des = df['column2'].str.split(expand=True).stack()

然后是des系列(我们从df ['column']中获得)在python中看起来像这样:

het
dag
calamiteit
bij
doen
gratis
dag
blijdorp
groet
burp
het
ik
ben

但是,我想从R到Python重新创建这段代码,我不知道如何做:

if (grepl("^\\s*$", des) == TRUE) { # if description is only whitespace then skip
    trns <- tibble(translatedText = "", detectedSourceLanguage = "", text = "")

尤其是grepl函数。

[在Python中等于什么?重新创建它的最佳Python代码是什么?谢谢

python r grepl
2个回答
0
投票

与grepl几乎完全等效的是re.match。看这个小例子:

import re
data = ["00het", "dags"]

matches = [re.match(r"\d{2}", str_) for str_ in data]

虽然第一个字符串匹配,但另一个字符串为None,因为其中没有两位数字。我希望这可能是您将表达式从R转换为python的一个很好的起点


0
投票

我完美地从上面重新创建了R脚本。这是Python代码:

 if [re.match(r'^\s*$', i) for i in des]:
        trns = i

所以,如果我有一系列这样的字符串:

root
wit
geel

with
asd

goed
black
red

然后用if语句运行它之后,我将得到如下结果:

[None,
None,
None,
None,
None,
None,
<re.Match object; span=(0, 1), match=' '>,
None,
<re.Match object; span=(0, 0), match=''>,
<re.Match object; span=(0, 1), match=' '>]
© www.soinside.com 2019 - 2024. All rights reserved.