2014-11-24 90 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>