首页 > 解决方案 > 如何计算 str.replace 执行的操作数?

问题描述

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

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

输出应该看起来像 -

Operated on 10 rows

标签: pythonregexpython-3.xstringcount

解决方案


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

推荐阅读