如何在包含冒号的单词前插入换行符

2024-04-29 08:25:12 发布

您现在位置: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。你知道吗

感谢您提前回复!你知道吗


Tags: 字符串agenicknamegenderpriceoldfemalecolor
3条回答

不可能将多个单词类别与执行它们的值区分开来,但是假设您可以将自己限制为单个单词类别,您可以使用以下内容:

import sys
data = "Breed: Pembroke Welsh Corgi Price: $2,200 Gender: Female Nickname: Koko"
words = data.split(' ')
for word in words:
    if word.endswith(':'):
        sys.stdout.write("\n"+word)
    else:
        sys.stdout.write(" "+word)
sys.stdout.write("\n")

产生输出:

Breed: Pembroke Welsh Corgi
Price: $2,200
Gender: Female
Nickname: Koko

正如奥斯汀在上面指出的,有些类别是短语而不是单词。没有简单的方法来区分“成熟时的黄色和白色大小”这样的东西,以确定新线应该走向何方。所以,你需要提前有一个详尽的清单,列出所有可能的类别。如果你能提供,有很多方法可以做到这一点。这里有一个简单的例子:

s = "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"

categories = ['Breed', 'Price', 'Gender:', 'Nickname', 'Age', 'Color/Markings',
              'Size at Maturity', 'Availability Date', 'Shipping Area',
              'Payment Method']

for cat in categories:
    s = s.replace(cat + ':', '\n' + cat + ':')

print(s)

不过,如果可能的话,最好先修复生成此数据的内容,以便它具有适当的分隔符。你知道吗

为什么没有人提出regex解决方案?:)

import re
txt = '''your text'''
re.sub(r'(\w+):', r'\n\1:', txt).strip()

如果原始的txt中有换行符,那么输出中可能会有两个换行符。它们可以很容易地移除:

re.sub(r'\n\n', r'\n', # Remove double line breaks
       re.sub(r'(\w+):',r'\n\1:',txt).strip())

此解决方案假定冒号前只有一个感兴趣的单词。事实上,可能无法决定如何拆分“装运区域:全球付款方式:货币”。是“发货区域:全球”和“付款方式:货币”还是“发货区域:全球付款”和“付款方式:货币”?你知道吗

相关问题 更多 >