python - 如何在 Python 中删除字符串/数据帧 [i] 的非特定字符
问题描述
在我的数据清理过程中,我发现了一些带有 inhbit 单个字符的字符串,这可能会影响我的分析
即“你好,请帮我解决这个问题”。
到目前为止,我只找到了删除特定字符的工具,比如
char= 's'
def char_remover(text:
spec_char = ''.join (i for i in text if i not in s text)
return spec_char
或 rsplit()、split() 函数,它们适用于删除字符串的第一个/最后一个字符。
最后,我想编写一个函数,从我的字符串/数据帧中删除所有单个字符(空白字符空白)。
我对这个问题的看法:
def spec_char_remover(text):
spec_char_rem= ''.join(i for i in text if i not len(i) <= 1)
return spec_char_rem
但这显然行不通。
提前致谢。
解决方案
你可以使用正则表达式:
>>> import re
>>> s = 'hello please help r me with this s question'
>>> re.sub(' . ', ' ', s)
'hello please help me with this question'
正则表达式中的“ .
”匹配任何字符。所以“ .
”匹配任何被空格包围的字符。您还可以使用 " \s.\s
" 来匹配任何被任何空格包围的字符。
推荐阅读
- javascript - python和javascript之间需要通信
- reactjs - 在表单组件的 Form.Items 中的 Ant Design“规则”中不起作用
- azure-active-directory - 如何查询成员列表及其基本资料,包括 Teams 用户 ID?
- android - Android 滚动视图如何在内部工作?
- c++ - why do i get an empty line as the first output?
- java - Java Stream过滤相同的字段但不同的标准
- c# - 由 HttpClientFactory 创建的长寿 HttpClient
- android - Can nested NavHosts both be the default nav host (defaultNavHost="true")?
- r - Kendall Correlation P-Value
- java - 适用于 Windows 的 JDK/JRE 安装