2014-11-24 149 views
0

我試圖將文本拆分爲段落。我想找到的第一行,並將其分配給一個變量,而線的其餘部分應格式化內<p></p>拆分換行符並刪除空行

text = "Firstline 

Secondline 

Third line" 

以下是我有:

text = unicode(ws.description) 

object.firstline = text.split('\n', 1)[0] #This works, and should not be wrapped in <p></p> 


bodytext = text.partition('\n')[2] 

object.body = ''.join('<p>'+L+'</p>' for L in bodytext.split('\n')) 

object.body返回此值

object.body = "<p></p> 
<p>Secondline</p> 
<p></p>  
<p>Third line</p> 
<p></p>" 

如何刪除空行,所以我沒有任何空<p></p>

編輯

這裏是工作的代碼(從阿什維尼喬杜裏的答案)

text = unicode(ws.description) 

if not "\n" in text: 
    object.firstline = text 
else: 
    first, rest = text.split('\n', 1) 

    object.firstline = first 

    object.body = '\n'.join(u'<p>{}</p>'.format(x) for x in rest.splitlines() if x) 

回答

1

'\n'首先分裂一次拿到第一線和其餘的行:

>>> first, rest = text.split('\n', 1) 
>>> first 
'Firstline' 
>>> rest 
'\nSecondline\n\nThird line' 

現在在環行(rest.splitlines())的休息和使用簡單的if條件刪除空行:

>>> print '\n'.join('<p>{}</p>'.format(x) for x in rest.splitlines() if x) 
<p>Secondline</p> 
<p>Third line</p> 
+0

我得到這個錯誤'ValueError:需要多個值1解包' – 2014-11-24 14:14:50

+0

@ Garreth00這意味着您的文本不包含換行符,即類似:'text ='first line''。 – 2014-11-24 14:16:55

+0

@ Garreth00'如果'\ n'不在文本中:打印'文本只包含一行'# – 2014-11-24 14:23:08

0
''.join('<p>'+L+'</p>' for L in bodytext.split('\n') if L) 
1

你只需要確定該字符串是否爲空之前加入它。

考慮:

>>> text = """Firstline 
... 
... Secondline 
... 
... Third line""" 

這將成爲:

>>> ''.join('<p>' + L + '</p>' for L in text.split('\n') if L) 
'<p>Firstline</p><p>Secondline</p><p>Third line</p>' 

text.split創建一個列表,其中你是通過迭代; if L檢查該列表中的非空值。

+0

@ garreth-00你也應該記住,那換行能是'\ r','\ n'或'\ r \ n'。所以,注意這個答案http://stackoverflow.com/a/21840976/764182 – dizpers 2014-11-24 14:23:16

0

使用str.splitlines作爲行邊界,然後使用str.join來加入字符串。

text = """Firstline 
Secondline 
Third line""" 

print '\n'.join('<p>'+l+'</p>' for l in text.splitlines() if l) 

輸出: -

>>> 
<p>Firstline</p> 
<p>Secondline</p> 
<p>Third line</p> 

打印最後兩行,

text = text.splitlines[1:] 
print '\n'.join('<p>'+l+'</p>' for l in text if l) 

輸出: -

>>> 
<p>Secondline</p> 
<p>Third line</p>