1. 程式人生 > >Python字串中大寫字母前增加空格的方法(字串用大寫字母分割)

Python字串中大寫字母前增加空格的方法(字串用大寫字母分割)

實現了需求,實際上很簡單,就是用re包:
import re

pattern="[A-Z]"
new_string=re.sub(pattern,lambda x:" "+x.group(0),old_string)
print new_string

另外,再總結一個需求,從連續的沒有空格的英文字串中提取出有意義的word,例如tableapplechairtablecupboard提取出:["table", "apple", "chair", "table", ["cupboard", ["cup", "board"]], ...],感覺這個需求也是很有意義的,Stack Overflow上已經有很多討論和較詳細的答案:https://stackoverflow.com/questions/8870261/how-to-split-text-without-spaces-into-list-of-words

,有人根據這些討論還開發一個Python包:wordninja,GitHub Repo的連結是:https://github.com/keredson/wordninja (word忍者)

發現其確實可以針對全是小寫字母的字串處理:

import wordninja

splited_words=wordninja.split(old_string.lower())
print splited_words
感覺這個工具確實造福人類啊!