2011-03-20 133 views
1

我正在處理一個文本,其中刪除了所有「\ n」(將兩個單詞合併爲一個,例如「我喜歡香蕉,這是一條新線和另一個。」)我現在要做的就是告訴Python尋找一個小寫字母組合,後跟大寫字母/標點符號,後跟大寫字母並插入一個空格。拆分python中的合併單詞

我認爲這對reg很簡單。表達式,但它不是 - 我找不到一個「插入」函數或任何東西,並且字符串命令似乎也沒有幫助。我該怎麼做呢? 任何幫助將不勝感激,我絕望的在這裏......

謝謝,帕特里克

回答

4

嘗試以下操作:

re.sub(r"([a-z\.!?])([A-Z])", r"\1 \2", your_string) 

例如:

import re 
lines = "I like bananasAnd this is a new line.And another one." 
print re.sub(r"([a-z\.!?])([A-Z])", r"\1 \2", lines) 
# I like bananas And this is a new line. And another one. 

如果要插入新行,而不是空間,更換爲r"\1\n\2"

+1

非常感謝你,你剛剛救了我的週末! – patrick 2011-03-20 04:20:46

0

嗯,有趣。您可以使用正則表達式的sub() function替換文本:

>>> import re 
>>> string = 'fooBar' 
>>> re.sub(r'([a-z][.!?]*)([A-Z])', r'\1 \2', string) 
'foo Bar' 
+0

多德。美元符號不是你插入組的方式。 :-) – 2011-03-20 03:14:52

+1

@Brandon:是的,剛剛意識到,謝謝。仍在思考Perl ;-) – Cameron 2011-03-20 03:15:27

1

使用re.sub你應該能夠作出這樣的劫掠小寫和大寫字母和替代他們相同的兩個字母的模式,但在之間的空間:

import re 
re.sub(r'([a-z][.?]?)([A-Z])', '\\1\n\\2', mystring) 
+0

這似乎產生以下內容:我喜歡banana \ 1 \ n \ 2nd這是一個新的lin \ 1 \ n \第二個另一個。爲了解決這個問題,使用\ 1 \ n \ 2 – Tom 2011-03-20 03:28:51

+0

Tom替換部分,我想你可能會在我的示例中嘗試使用時意外地在第二個字符串常量前加了一個'r'字符。 Python字符串「\\ 1 \ n \\ 2」是一系列字符'\ 1 \ 2'。 – 2011-03-21 02:03:32

0

如果你真的不除了在句子的開始處有任何大寫字母,它可能是最簡單的循環字符串。

>>> import string 
>>> s = "a word endsA new sentence" 
>>> lastend = 0 
>>> sentences = list() 
>>> for i in range(0, len(s)): 
... if s[i] in string.uppercase: 
...  sentences.append(s[lastend:i]) 
...  lastend = i 
>>> sentences.append(s[lastend:]) 
>>> print sentences 
['a word ends', 'A new sentence'] 
0

這裏的另一種方法,避免了正則表達式和不使用任何進口圖書館,只是內置插件...

s = "I like bananasAnd this is a new line.And another one." 
with_whitespace = '' 
last_was_upper = True 
for c in s: 
    if c.isupper(): 
     if not last_was_upper: 
      with_whitespace += ' ' 
     last_was_upper = True 
    else: 
     last_was_upper = False 
    with_whitespace += c 

print with_whitespace 

產量:

I like bananas And this is a new line. And another one.