如何用Python正则表达式有效移除中文文本中的多余空格?

2026-06-09 17:124阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计335个文字,预计阅读时间需要2分钟。

如何用Python正则表达式有效移除中文文本中的多余空格?

在将PDF转换为文本时,常有多余的空白格,影响数据感知。需去除文本中的多余空格,保留英文字符间的正常空格。例如:输入:我昨天赚了10个亿,老百二‘输出:我昨天赚了10个亿

在pdf转为文本的时候,经常会多出空格,影响数据观感,因此需要去掉文本中多余的空格,而文本中的英文之间的正常空格需要保留,输入输出如下:

input:我今天 赚了 10 个亿,老百姓very happy。

output:我今天赚了10个亿,老百姓very happy。

如何用Python正则表达式有效移除中文文本中的多余空格?

代码

def clean_space(text): """" 处理多余的空格 """ match_regex = re.compile(u'[\u4e00-\u9fa5。\.,,::《》、\(\)()]{1} +(?<![a-zA-Z])|\d+ +| +\d+|[a-z A-Z]+') should_replace_list = match_regex.findall(text) order_replace_list = sorted(should_replace_list,key=lambda i:len(i),reverse=True) for i in order_replace_list: if i == u' ': continue new_i = i.strip() text = text.replace(i,new_i) return text

python去除英文单词之间多余的空格

re.sub(" +", " ", s)

import re s = " info has been found (+/- 100 pages, and 4.5 mb of .pdf files) now i have to wait untill our team leader has processed it and learns html. " re.sub(" +", " ", s)

' '.join(s.split())

s = " info has been found (+/- 100 pages, and 4.5 mb of .pdf files) now i have to wait untill our team leader has processed it and learns html. " s = ' '.join(s.split()) s

更多关于python使用正则表达式去除多余空格方法请查看下面的相关链接

本文共计335个文字,预计阅读时间需要2分钟。

如何用Python正则表达式有效移除中文文本中的多余空格?

在将PDF转换为文本时,常有多余的空白格,影响数据感知。需去除文本中的多余空格,保留英文字符间的正常空格。例如:输入:我昨天赚了10个亿,老百二‘输出:我昨天赚了10个亿

在pdf转为文本的时候,经常会多出空格,影响数据观感,因此需要去掉文本中多余的空格,而文本中的英文之间的正常空格需要保留,输入输出如下:

input:我今天 赚了 10 个亿,老百姓very happy。

output:我今天赚了10个亿,老百姓very happy。

如何用Python正则表达式有效移除中文文本中的多余空格?

代码

def clean_space(text): """" 处理多余的空格 """ match_regex = re.compile(u'[\u4e00-\u9fa5。\.,,::《》、\(\)()]{1} +(?<![a-zA-Z])|\d+ +| +\d+|[a-z A-Z]+') should_replace_list = match_regex.findall(text) order_replace_list = sorted(should_replace_list,key=lambda i:len(i),reverse=True) for i in order_replace_list: if i == u' ': continue new_i = i.strip() text = text.replace(i,new_i) return text

python去除英文单词之间多余的空格

re.sub(" +", " ", s)

import re s = " info has been found (+/- 100 pages, and 4.5 mb of .pdf files) now i have to wait untill our team leader has processed it and learns html. " re.sub(" +", " ", s)

' '.join(s.split())

s = " info has been found (+/- 100 pages, and 4.5 mb of .pdf files) now i have to wait untill our team leader has processed it and learns html. " s = ' '.join(s.split()) s

更多关于python使用正则表达式去除多余空格方法请查看下面的相关链接