前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[785]python去掉字符串中多余的空格

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

作者头像
周小董
发布2020-04-21 10:52:27
1.4K0
发布2020-04-21 10:52:27
举报
文章被收录于专栏:python前行者
代码语言:javascript
复制
# -*- 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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/04/18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档