[英]Python add a space between special characters and words
I am working on a data science project and I have an issue. 我正在做一个数据科学项目,但是有一个问题。 I have an array full of string like the following string and I want to add a space between the words and between the special characters
我有一个充满字符串的数组,例如以下字符串,我想在单词之间和特殊字符之间添加一个空格
sentence[i] = 'This is a⓵⓶⓷string'
and I expect something like that: 我期望这样的事情:
sentence[i] = 'This is a ⓵ ⓶ ⓷ string'
My last try: 我的最后尝试:
l=[]
for i in lines:
for j in i:
if j.isalpha() == False:
l.append(i.split())
else:
l.append(i)
print(l)
for i in l:
s = ' '.join(i)
You could simply scan the complete line and selectively add space for each character that is neither alphabet nor a space. 您可以简单地扫描整行,并为每个既不是字母也不是空格的字符添加空格。
s = 'This is a⓵⓶⓷string'
t = ''
for x in s :
if not str.isalpha(x) and x != ' ' :
if t[-1] != ' ':
t+= ' '
t += x
t += ' '
else: t += x
this works for example you have given. 例如您给出的作品。
使用正则表达式来完成该任务,特别是将re.sub
与反向引用一起使用,以便将匹配的字符用空格包围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.