【问题标题】:How to add space between words and punctuation in a column?如何在列中的单词和标点符号之间添加空格?
【发布时间】:2021-05-26 22:18:01
【问题描述】:
我在数据框中有一列(字符串),单词和标点符号之间有多个空格。
我需要:
- 在标点符号之间添加空格
- 删除重复的空格
我要找的标点符号是/+-。
我的数据框:
col A
'this/is a+ string'
'this+is+a string'
我期望的输出:
col B
'this / is a + string'
'this + is + a string'
【问题讨论】:
标签:
python
pandas
dataframe
【解决方案1】:
我解决这个问题的方法是分两步:首先,在 pontuation 之间添加空格,然后检查是否有任何连续的空格。第一步,我使用了一个名为punctuation_space 的函数作为“repl”参数传递给re.sub()。
import re
def punctuation_space(match_obj):
""" return whatever matched surrounded by spaces """
return ' ' + match_obj.group() + ' '
def fn(string):
# first step
string = re.sub(r'[+/-]', punctuation_space, string)
# second step
return re.sub(r' {2,}', ' ', string)
查看以上代码:
import pandas as pd
original_col = ['this/is a+ string', 'this+is+a string']
s = pd.Series(original_col)
print(s)
print(s.apply(fn))
输出:
0 this/is a+ string
1 this+is+a string
dtype: object
0 this / is a + string
1 this + is + a string
dtype: object
【解决方案2】:
你可以试试:
df['col A'] = df['col A'].apply(lambda y: " ".join((re.sub(r'([+/-])', lambda x: ' ' + x.group()+' ' , y)).split()) , 1)
或者:
df['col A'] = df['col A'].str.replace(r'([+/-])', lambda x: ' ' + x.group()+' ', regex=True).apply(lambda x: ' '.join(x.split()))