python - 使用 re.sub 删除两个字符之间的空格

python - remove whitespace between two characters using re.sub

我有一对列,像这样:

x = ["a b williams", "e g", "z z specialists"]
y = ["j j winston", "hb d party supplies", "t t ice cream"]
df = pd.DataFrame(x,y)

我希望能够使用 re.sub 删除两个单个字符之间的白色 space。我尝试了以下方法:

re.sub("(?<=\w\b)"\s"(?=\w\b)", "", df)

但是,当我 运行 代码时,出现以下错误。

SyntaxError: unexpected character after line continuation character

我不确定我做错了什么。期望的结果是:

jj winston             ab williams
hb d party supplies              eg
tt ice cream           zz specialists

请指教。任何建议表示赞赏。

您可以使用

(?<=\b[^\W\d_])\s(?=[^\W\d_]\b)
(?<=\b\w)\s(?=\w\b)

regex demo。请注意 [^\W\d_] 模式匹配 Python re 中的任何 Unicode 字母。 \w 匹配 Unicode 字母、数字、_ 和一些变音符号和其他连接符。

详情

  • (?<=\b[^\W\d_]) - 正后视匹配紧接在整个单词前面的单个字母的位置(因为它前面有单词边界)
  • \s - 空白字符
  • (?=[^\W\d_]\b) - 匹配一个位置的正向前瞻,该位置紧随其后的是单个字母作为整个单词(因为它后跟单词边界)。

这是一个 Pandas 演示:

x = ["a b williams", "e g", "z z specialists"]
y = ["j j winston", "h d party supplies", "t t ice cream"]
df = pd.DataFrame(x,y)
rx = r'(?<=\b[^\W\d_])\s(?=[^\W\d_]\b)'
df.index = df.index.to_series().replace(rx, '', regex=True)
df = df.replace(rx, '', regex=True)
# => df
#                                 0
# jj winston            ab williams
# hd party supplies              eg
# tt ice cream       zz specialists

由于DataFrame.replaceregex=True不涉及索引列,需要单独处理,所以增加了df.index = df.index.to_series().replace(rx, '', regex=True)行代码。

您的正则表达式非常接近要求,可以稍微修改如下:

r'(?<=\b\w)(\s)(?=\w\b)'

请注意使用原始引号 r'...' 这样您就不需要在正则表达式中使用双 \ for。

Regex Demo

更好地编译正则表达式以加快处理速度,因为它被多次使用

pattern = re.compile(r'(?<=\b\w)(\s)(?=\w\b)')

然后重复使用您的代码:

x = ["a b williams", "e g", "z z specialists"]
y = ["j j winston", "h d party supplies", "t t ice cream"]
df = pd.DataFrame(x,y)

转换索引:

df.index = df.index.to_series().str.replace(pattern, '')

转换数据列:

df[0] = df[0].str.replace(pattern, '')

错误说明:

  1. 不能在整个pandasDataFrame上直接使用re.sub
  2. 您的正则表达式包含 4 个引号 ",其中第二个 " 结束正则表达式,因此正则表达式的后续部分被 \ 标记视为续行,续行后的字符被视为无效

使用re.sub,我建议如下:

# your lists    
x = ["a b williams", "e g", "z z specialists"]
y = ["j j winston", "hb d party supplies", "t t ice cream"]

# replacements
x = [re.sub(r'(\b\w)(\s)(\w\b)', r'', el) for el in x]
y = [re.sub(r'(\b\w)(\s)(\w\b)', r'', el) for el in y]

# pd dataframe after the process
df = pd.DataFrame(x,y)