【问题标题】:Removing Characters With Regular Expression in List Comprehension in PythonPython中列表理解中使用正则表达式删除字符
【发布时间】:2021-09-16 13:58:30
【问题描述】:

我正在学习 python,我正在尝试做一些文本预处理,我一直在阅读和借鉴 Stackoverflow 的想法。我能够想出下面的公式,但它们似乎没有达到我的预期,而且它们也没有抛出任何错误,所以我很难过。

首先,在 Pandas 数据框列中,我试图删除单词中的第三个连续字符;这有点像对应该有两个连续字符而不是三个字符的单词进行拼写检查

buttter = butter
bettter = better
ladder = ladder

我使用的代码如下:

import re
docs['Comments'] = [c for c in docs['Comments'] if re.sub(r'(\w)\1{2,}', r'\1', c)]

在第二种情况下,我只想用最后一个替换多个标点符号。

????? = ?
..... = .
!!!!! = !
----  = -
***** = *

我的代码是:

docs['Comments'] = [i for i in docs['Comments'] if re.sub(r'[\?\.\!\*]+(?=[\?\.\!\*])', '', i)]

【问题讨论】:

    标签: python-3.x regex list-comprehension


    【解决方案1】:

    看起来你想用

    docs['Comments'] = docs['Comments'].str.replace(r'(\w)\1{2,}', r'\1\1', regex=True)
        .str.replace(r'([^\w\s]|_)(\1)+', r'\2', regex=True)
    

    r'(\w)\1{2,}' 正则表达式找到三个或更多重复的单词字符,\1\1 用两个它们的出现替换。见this regex demo

    r'([^\w\s]|_)(\1)+' 正则表达式匹配重复的标点字符并将最后一个捕获到第 2 组,因此\2 将匹配替换为最后一个标点字符。见this regex demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 2014-06-25
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 2010-10-23
      相关资源
      最近更新 更多