python - 正则表达式没有用空格替换字符串
问题描述
我已经制作了这段代码来用空格替换所有非字母,但我没有得到空格,这样做是为了清除所有空格
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”]]”
我想要一个像“[[”这是样本“],[”这是样本二“]]”这样的文本
解决方案
这给了你你想要的,使用 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]"
推荐阅读
- spring - 为什么@RestController 默认使用单例范围?
- powershell - 如何使用 Powershell 脚本在远程计算机上查找 PST 文件
- php - 数据表页面就像只有一页一样工作
- angular - 单击铅笔图标编辑内容
- javascript - JavaScript 对象语法和符号
- json - 从 Bigquery 中的 json 获取数组
- javascript - React Native 和 Apollo 客户端
- javascript - 单击 highcharts 中的图例时,柱形图未重置
- unity3d - 如何在我的 3d FPS 游戏中让手跟随相机?
- java - ClassCastException:未经检查的演员表:“java.lang.Object []”到“list.TestCastO”
[]