2017-08-16 27 views
-4

代碼在Python可以像這樣Python的正則表達式爲多個分隔符,包括使用正則表達式雙引號

輸入執行的東西:

> https://test.com, 2017-08-14, "This is the title with , and "anything" in it", "This is the paragraph also with , and "anything" in it" 

理想的輸出:

['https://test.com', '2017-08-14', 'This is the title with , and "anything" in it', 'This is the paragraph also with , and "anything" in it'] 
+5

歡迎來到Stack Overflow。這不是代碼或正則表達式寫入服務。一旦你努力自己解決問題並遇到困難,我們很樂意提供幫助。當你這樣做時,你可以解釋你遇到的問題,包含*相關*代碼,並且詢問有關該代碼的**特定問題**,我們可以嘗試提供幫助。祝你好運。 –

+1

不客氣。 – dat3450

回答

0

有您可以使用多種方法拆分。

香草內置分割方法接受分隔符作爲一個參數,並會做什麼是對錫寫的,正是在已經指定的任何分隔符拆分字符串,返回它作爲一個列表。

在你的情況,你想要的分隔符爲「」但只有不在引號內的逗號。在一般情況下,這樣的事情你可以做:

foo = 'https://test.com, 2017-08-14, "This is the title with , and "anything" in it", "This is the paragraph also with , and "anything" in it"' 


print foo.split(',') 
#but this has the caveat that you don't have any ','s within your input as those will become delimitation points as well, which you do not want. 

在這種特殊情況下,你也可以匹配的發言權「」 但是這也將失敗,因爲你的輸入有一個元素title with , and "any,這將是不正確的拆分。

而在這種情況下,我們可以使用shlex和使用它的方法split。現在,這種拆分方法將使用空格來設置分隔符。

那麼,這樣做的:

print [_ for _ in shlex.split(foo)] 

會給我們一些更接近我們想要的東西,但不完全:

>>> ['https://test.com,', '2017-08-14,', 'This is the title with , and anything in it,', 'This is the paragraph also with , and anything in it'] 

可以看出,它在要素討厭逗號,我們不想要。

不幸的是,我們不能做

print [_[:-1] for _ in shlex.split(foo)] 

爲將切斷在 '它' 最後 'T',但我們可以使用內置的字符串在

rstrip 

方法

和匹配任何逗號在每個元件的端部:

print [_.rstrip(',') for _ in shlex.split(foo)] 

給輸出:

>>> ['https://test.com', '2017-08-14', 'This is the title with , and anything in it', 'This is the paragraph also with , and anything in it'] 

這是非常接近我們想要什麼,但不完全是! (缺少的圍繞‘什麼’ - shlex吃掉這件事!)

但是,我們非常接近,我會離開,輕微珍聞爲你的功課,你應該嘗試的解決方案。首先像其他人發佈的那樣。

資源:

https://www.tutorialspoint.com/python/string_split.htm

https://docs.python.org/2/library/shlex.html

附:提示:也看看csv模塊。

+0

這是不正確的。 OP不希望在''''內部'''被分割,見理想輸出。 – lincr

+0

@lincr Oopsies,你說的沒錯,它會以任何逗號分割字符串,認爲這是非常微不足道的問題。我匆匆地看了一下輸入= p。我將代碼更新了一些,但留下了他的問題讓他真正嘗試完成,謝謝。 – srath