【问题标题】:How to count no.of operations performed by str.replace?如何计算 str.replace 执行的操作数?
【发布时间】:2019-06-19 03:42:36
【问题描述】:

我有一个带有列 cmets 的数据框,我使用正则表达式删除数字。我只想计算这种模式改变了多少行。即计算 str.replace 操作的行数。

df['Comments']=df['Comments'].str.replace('\d+', '')

输出应该看起来像-

Operated on 10 rows

【问题讨论】:

  • 保存df['Comment'],然后在新旧值之间进行比较,计算差异,会不会是作弊?
  • @ShadowRanger 不,这是唯一的方法。
  • 我已经考虑过了,如果没有人能够回答更好的解决方案,这是我最后的选择:P

标签: python regex python-3.x string count


【解决方案1】:

re.subn() 方法返回执行的替换次数和新字符串。

示例:text.txt 包含以下几行内容。

No coments in the line 245
you can make colmments in line 200 and 300
Creating a list of lists with regular expressions in python ...Oct 28, 2018
re.sub on lists - python 

示例代码:

count = 0   
for line in open('text.txt'):
    if (re.subn(r'\d+',"", line)[1]) > 0:
        count+=1
print("operated on {} rows".format(count))

对于熊猫:

data['comments'] = pd.DataFrame(open('text.txt', "r"))
count = 0
for line in data['comments']:
    if (re.subn(r'\d+',"", line)[1]) > 0:
        count+=1

print("operated on {} rows".format(count))

输出:

operated on 3 rows

【讨论】:

  • OP 不想获取替换的计数,只获取发生替换的行数。
  • 我的答案已经修改,请检查
  • 是的,在 pandas 中也可以通过使用正则表达式来获取发生替换的行数。我已经修改了我的答案,请检查。希望答案符合您的要求
  • 很抱歉,我确实尝试了 pandas,但它仍然给出操作计数而不是行计数。
  • 如果可能的话,你能分享一下你试过的代码吗?
【解决方案2】:

看看有没有帮助

import re
op_regex = re.compile("\d+")
df['op_count'] = df['comment'].apply(lambda x :len(op_regex.findall(x)))
print(f"Operation on {len(df[df['op_count'] > 0])} rows")

使用 findall 返回匹配字符串的列表。

【讨论】:

  • 这行得通。但我确实有操作,我也只执行小写。我想我会弄清楚这一点。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多