首页 > 解决方案 > 正则表达式没有用空格替换字符串

问题描述

我已经制作了这段代码来用空格替换所有非字母,但我没有得到空格,这样做是为了清除所有空格

edit = [["this, is sample 1."],["this!is @ sample two.*"]]
def clearpunch(sentence):
    clean = re.sub(r"'|\W|\d|_",r" ",sentence)
    return clean
edit = edit.map(clearpunch)
edit

得到这样的文本“[[“thisissample”],[“thisissampletwo”]]”

我想要一个像“[[”这是样本“],[”这是样本二“]]”这样的文本

标签: pythonregex

解决方案


这给了你你想要的,使用 map 功能:

import re

def clearpunch(sentence):
    clean = re.sub(r"'|\W|\d|_",r" ",sentence)
    return clean

edit = [["this, is sample 1."],["this!is @ sample two.*"]]

answer = [list(map(clearpunch, item)) for item in edit]

print(answer)

输入:

[["this, is sample 1."],["this!is @ sample two.*"]]

输出:

[['this  is sample   '], ['this is   sample two  ']]

如果你只想要小写英文字母,你可以使用这个正则表达式模式:r"[^a-z]"


推荐阅读