python - 除撇号外,python 在所有空格和标点符号处重新拆分
问题描述
我想用除撇号之外的所有空格和标点符号来分割一个字符串。最好还是使用单引号作为分隔符,除非它是撇号。我也想保留分隔符。示例字符串
words = """hello my name is 'joe.' what's your's"""
到目前为止,这是我的 re 模式,splitted = re.split(r"[^'-\w]",words.lower())
我尝试在 ^ 字符后加上单引号,但它不起作用。
我想要的输出是这个。splitted = [hello,my,name,is,joe,.,what's,your's]
解决方案
在拆分后简单地处理您的列表可能更简单,而不首先考虑它们:
>>> words = """hello my name is 'joe.' what's your's"""
>>> split_words = re.split(r"[ ,.!?]", words.lower()) # add punctuation you want to split on
>>> split_words
['hello', 'my', 'name', 'is', "'joe.'", "what's", "your's"]
>>> [word.strip("'") for word in split_words]
['hello', 'my', 'name', 'is', 'joe.', "what's", "your's"]
推荐阅读
- macos - 无法让 YouCompleteMe 工作 - 几个下游安装问题
- zshrc - 在zsh中,如何将此片段存储为环境变量以在另一个命令中输出
- javascript - d3.js 向外部 svg 文件添加缩放功能
- objective-c - Big Sur 11.5 的辅助功能 API 坏了?
- node.js - 使用 peerjs socket.io nodeJS 进行视频通话有时才有效
- python - 在 Tkinter python 中自动检查复选框的功能
- javascript - 使用 JavaScript 在 Bootstrap 4 无序列表中获取活动列表项
- node.js - 为什么 testDouble 不能模拟 3rd 方函数?
- .htaccess - 使用 .htaccess 将用户从我们的 amp 页面重定向
- javascript - 数据未填充在 MongoDB 中