首页 > 解决方案 > 如何在 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

但这显然行不通。

提前致谢。

标签: pythonpandasstringfunctiondata-cleaning

解决方案


你可以使用正则表达式:

>>> import re
>>> s = 'hello please help r me with this s question'
>>> re.sub(' . ', ' ', s)
'hello please help me with this question'

正则表达式中的“ .”匹配任何字符。所以“ . ”匹配任何被空格包围的字符。您还可以使用 " \s.\s" 来匹配任何被任何空格包围的字符。


推荐阅读