python中文字符串多余空格_[785]python去掉字符串中多余的空格

该代码段提供了一个Python函数,用于清除字符串中多余的空格。它首先定义了判断中文和英文字符的函数,然后通过正则表达式找到所有空格位置,并根据前后字符类型决定是否移除。主要应用于处理包含中文和英文的字符串,保持单词间的适当间隔。
摘要由CSDN通过智能技术生成

# -*- coding:utf-8 -*-

import re

# 检验某个字符是否是中文字符

def is_chinese(char):

if '\u4e00' <= char <= '\u9fa5':

return True

return False

# 检验某个字符是否是英文文字符或数字

def is_english_char(char):

if 97<=ord(char)<=122 or 65<=ord(char)<=90 or char.isdigit():

return True

return False

# 去掉字符串之间多余的空格

def del_space(strs_v):

strs_v = strs_v.strip()

# 计算出字符串中空格的所有位置,如果没有空格返回出空list

index_list = [i.start() for i in re.finditer(' ', strs_v)] # i.span()

remove_index=[]

for index in index_list:

# # 如果空格字符串前面和后面有一个中文,去掉空格

# if is_chinese(strs_v[index-1]) or is_chinese(strs_v[index+1]):

# remove_index.append(index)

# 去掉空格前面的一个空格,如果英文里边中间隔了两个空格,去掉空格后面的一个空格的话,英文会连在一起

# elif strs_v[index - 1] == ' ': # or strs_v[index + 1]==' '

# remove_index.append(index)

#空格前面不是字母或数字

if not(is_english_char(strs_v[index-1])):

remove_index.append(index)

#空格前面是字母或数字,空格后面不是字母和数字且后面不是空格

elif is_english_char(strs_v[index-1]) and (not is_english_char(strs_v[index+1]) and strs_v[index + 1]!=' '):

remove_index.append(index)

if remove_index !=[]:

strs_v = ''.join([strs_v[i] for i in range(len(strs_v)) if i not in remove_index])

return strs_v

if __name__ == '__main__':

a='ALWIN VANGARD INVESTMENT LTD. '

print(del_space(a))

a='中融 a 1 ( 信托 ansnns fff 展博 Lindman 6 Global Growth PE Fund'

print(del_space(a))

print(del_space(del_space(a)))

参考:https://www.jianshu.com/p/25def1847697

https://blog.csdn.net/baidu_15113429/article/details/80651091

本文同步分享在 博客“周小董”(CSDN)。

如有侵权,请联系 support@oschina.cn 删除。

本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值