2016-12-29 146 views
0

我试图以编程方式格式化一个pdf菜单,并且一切都进行得很顺利,直到我注意到某些换行符打破了该模式。这是我的原始文本的部分看起来像:删除Python中的特定换行符

LATIN 
Saturday & Sunday: 
Build Your Own Breakfast Burrito, Scrambled Eggs, Cheesy Eggs, Latin Tofu 
Scramble, Latin Roasted Vegetables 
DESSERT 
Daily: 
Assorted Pastries 

我注意到,有些项目(如拉丁豆腐争夺)有摆在他们中间的换行符。鉴于菜单项是可变的,并且在其他地方可能会有额外的换行符,有什么办法可以删除逗号之间出现的换行符(因为所有的项都是以逗号分隔的)?

编辑: 最后的结果将理想是这个样子:

LATIN 
Saturday & Sunday: 
Build Your Own Breakfast Burrito, Scrambled Eggs, Cheesy Eggs, Latin Tofu Scramble, Latin Roasted Vegetables 
DESSERT 
Daily: 
Assorted Pastries 
+1

您可以包括你想要的最终结果? – MYGz

+0

刚刚添加了一个可能的最终结果 – SebastianLloret

+1

[我如何在Python中删除(chomp)换行符?](http://stackoverflow.com/questions/275018/how-can-i-remove-chomp-a-换行符在Python中) –

回答

1

下面MULTILINE使用re.sub用正则表达式的尝试,它只是替换成逗号之前换行和下一行包含逗号

但是,如果换行符位于最后一项,例如,它将不起作用。拉丁烤蔬菜

txt = ''' 
LATIN 
Saturday & Sunday: 
Build Your Own Breakfast Burrito, Scrambled Eggs, Cheesy Eggs, Latin Tofu 
Scramble, Latin Roasted Vegetables 
DESSERT 
Daily: 
Assorted Pastries 
''' 

import re 
newtxt = re.sub('(,[^\r\n]*?)[\r\n](?=[^\r\n]+?,)', r'\1 ', txt, re.MULTILINE) 
# LATIN 
# Saturday & Sunday: 
# Build Your Own Breakfast Burrito, Scrambled Eggs, Cheesy Eggs, Latin Tofu Scramble, Latin Roasted Vegetables 
# DESSERT 
# Daily: 
# Assorted Pastries 
1

在Python中你可以使用line.strip('\n')line.strip('\t')除去换行符和水龙头的空间。或者,您可以使用replace('\ n','')从String行中删除所有换行符空格。

>>> line="Welcomes\n" 
>>> line.replace('\n','') 
'Welcomes' 
>>> 

或者,你可以使用rstrip()方法从字符串行中删除所有的换行符空间

>>> line.rstrip() 
'Welcomes' 
+0

我已经看过rstrip()和strip()以及replace()。我只想在逗号之间替换换行符。 – SebastianLloret