溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python使用正則表達(dá)式去除中文文本多余空格,保留英文之間空格方法詳解

發(fā)布時(shí)間:2020-09-29 08:52:32 來源:腳本之家 閱讀:432 作者:六神就是我 欄目:開發(fā)技術(shù)

在pdf轉(zhuǎn)為文本的時(shí)候,經(jīng)常會(huì)多出空格,影響數(shù)據(jù)觀感,因此需要去掉文本中多余的空格,而文本中的英文之間的正??崭裥枰A?,輸入輸出如下:

input:我今天 賺了 10 個(gè)億,老百姓very happy。

output:我今天賺了10個(gè)億,老百姓very happy。

代碼

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

更多關(guān)于python使用正則表達(dá)式去除多余空格方法請(qǐng)查看下面的相關(guān)鏈接

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI