【问题标题】:simplest python equivalent to R's gsub最简单的python相当于R的gsub
【发布时间】:2016-12-10 22:24:01
【问题描述】:

是否有与 R 的 gsub 函数等效的简单/单行 python?

strings = c("Important text,      !Comment that could be removed", "Other String")
gsub("(,[ ]*!.*)$", "", strings) 
# [1] "Important text" "Other String"  

【问题讨论】:

    标签: python r python-2.7


    【解决方案1】:

    对于字符串:

    import re
    string = "Important text,      !Comment that could be removed"
    re.sub("(,[ ]*!.*)$", "", string)
    

    由于您将问题更新为字符串列表,因此您可以使用列表推导。

    import re
    strings = ["Important text,      !Comment that could be removed", "Other String"]
    [re.sub("(,[ ]*!.*)$", "", x) for x in strings]
    

    【讨论】:

    • 看起来re.sub 有一个计数参数。在 R 中,gsub 删除模式的所有实例,因此gsub("th", "", "this that other") 将返回“在 oer”。你知道 count 的参数会告诉 python 删除模式的所有实例吗?
    • @Imo per the docs -- "可选参数 count 是要替换的模式出现的最大数量;count 必须是非负整数。如果省略或为零,所有出现将被替换。模式的空匹配仅在与前一个匹配不相邻时被替换,因此 sub('x*', '-', 'abc') 返回 '-abc-'。"
    • 如果我想把它应用到整个列表/列而不是一个字符串怎么办?
    【解决方案2】:

    gsub 是 python 中的普通sub - 也就是说,默认情况下它会进行多次替换。

    re.sub 的方法签名是sub(pattern, repl, string, count=0, flags=0)

    如果您希望它进行一次替换,请指定 count=1:

    In [2]: re.sub('t', 's', 'butter', count=1)
    Out[2]: 'buster'
    

    re.I 是不区分大小写的标志:

    In [3]: re.sub('here', 'there', 'Here goes', flags=re.I)
    Out[3]: 'there goes'
    

    你可以传递一个接受匹配对象的函数:

    In [13]: re.sub('here', lambda m: m.group().upper(), 'Here goes', flags=re.I)
    Out[13]: 'HERE goes'
    

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 1970-01-01
      • 2014-10-31
      • 2017-09-10
      • 2016-03-19
      • 1970-01-01
      • 2011-06-25
      • 2016-04-01
      • 2012-08-25
      相关资源
      最近更新 更多