如何删除 Python 中 string/dataframe[i] 的非特定字符
How to remove non-specific char of a string/dataframe[i] in Python
在我的数据清理过程中,我发现一些字符串包含一个可能会影响我的分析的字符
即'hello please help r me with this s question'.
直到现在我只找到了删除特定字符的工具,比如
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() 函数,它们适用于删除字符串的第一个/最后一个字符。
最后,我想编写一个函数,从我的 string/dataframe 中删除所有单个字符(空白字符空白)。
我对这个问题的看法:
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
”来匹配被任何空格包围的任何字符。
在我的数据清理过程中,我发现一些字符串包含一个可能会影响我的分析的字符
即'hello please help r me with this s question'.
直到现在我只找到了删除特定字符的工具,比如
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() 函数,它们适用于删除字符串的第一个/最后一个字符。
最后,我想编写一个函数,从我的 string/dataframe 中删除所有单个字符(空白字符空白)。
我对这个问题的看法:
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
”来匹配被任何空格包围的任何字符。