简体   繁体   English

使用正则表达式在特定模式前插入回车

[英]Use Regex to insert a carriage return before a particular pattern

I have scraped a website here is the result:我在这里抓取了一个网站,结果如下:

Description
Cap: 4-9 cm Pale brown - often lighter towards the edge. 
Viscid when wet.Gills: Pale clay-brown. Free. Gill edge exude droplets 
when moist which dry to form dark spots.Stem: Off-white. Mealy towards 
the apex.Spores: Clay-brownFlesh: Firm, white. Smell of 
radishesHabitat: In groups or rings on the ground in mixed 
woodlandFrequency: Very Common

I need to add a carriage before the words which precede the colon eg.我需要在冒号前面的单词之前添加一个马车,例如。 \\r\\nGills: in order to make the information more readable. \\r\\nGills:为了使信息更具可读性。

Is re.sub() the best way to do this? re.sub() 是最好的方法吗?

text_with_rc=re.sub(r'\.\s*',r'.\r\n',the_text)

Yes re.sub is required for this.是的,这需要 re.sub。 Try the below pattern试试下面的模式

str1=re.sub(r'(\w*:)',r'\r\n\1',string)
>>> print str1
Description


Cap: 4-9 cm Pale brown - often lighter towards the edge. 
Viscid when wet.

Gills: Pale clay-brown. Free. Gill edge exude droplets 
when moist which dry to form dark spots.

Stem: Off-white. Mealy towards 
the apex.

Spores: Clay-

brownFlesh: Firm, white. Smell of 


radishesHabitat: In groups or rings on the ground in mixed 


woodlandFrequency: Very Common
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM