python - 如何在包含冒号的单词之前插入换行符
问题描述
我有一个全是一行的字符串,例如:
Breed: Pembroke Welsh Corgi Price: $2,200 Gender: Female Nickname: Koko
Age: 9 Weeks Old Color/Markings: yellow and white Size at Maturity:
Medium Availability Date: 09/30/2018 Shipping Area: Worldwide Payment
Method: Money Order/Cashier's Check, Paypal, Credit Cards, Cash
我希望输出是:
Breed: Pembroke Welsh Corgi
Price: $2,200
Gender: Female
Nickname: Koko
等等等等。基本上\n
在以冒号结尾的新类别之前插入一个。
感谢您提前回复!
解决方案
为什么没有人提出正则表达式解决方案?:)
import re
txt = '''your text'''
re.sub(r'(\w+):', r'\n\1:', txt).strip()
如果 original 中有换行符txt
,您最终可能会在输出中出现双换行符。它们可以很容易地删除:
re.sub(r'\n\n', r'\n', # Remove double line breaks
re.sub(r'(\w+):',r'\n\1:',txt).strip())
此解决方案假定冒号前只有一个感兴趣的单词。事实上,可能无法决定如何拆分“Shipping Area: Worldwide Payment Method: Money”。是“收货地区:全球”和“付款方式:金钱”还是“收货地区:全球付款”和“方法:金钱”?
推荐阅读
- c# - Xbox One 上的 OneDrive SDK 或 Windows 工具包 OneDrive 服务
- c++ - 定义一个工厂函数,它返回一个指向在这个工厂函数中创建的函数的指针
- html - 使用引导网格系统以响应方式将图像放置在 div 旁边
- stripe-payments - Stripe - 使用 PaymentIntent 的订阅 + 预付费用
- sql - 查询工作表时如何修复vba中的“自动化错误”
- javascript - SVG 不与 android 6 和 cordova 一起显示
- .net - WCF Web 服务通过 HTTPS 返回 404,但通过 HTTP 工作
- excel - 将多个工作簿合并为一个
- python - KeyError:“[] 在轴中找不到”,同时用熊猫删除行
- mysql - SQL Join 3 个空值的表