我试图将文本拆分为段落。我想找到的第一行,并将其分配给一个变量,而线的其余部分应格式化内<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)
我得到这个错误'ValueError:需要多个值1解包' – 2014-11-24 14:14:50
@ Garreth00这意味着您的文本不包含换行符,即类似:'text ='first line''。 – 2014-11-24 14:16:55
@ Garreth00'如果'\ n'不在文本中:打印'文本只包含一行'# – 2014-11-24 14:23:08