[英]format multiline string with python
我需要在 python 中格式化下面显示的多行字符串。我尝试了很多方法,但结果并不理想。
AMAZON
IPHONE: 700
SAMSUNG: 600
=============
WALMART
IPHONE: 699
===========
ALIBABA
SONY: 500
因此,以上数据代表在线商店及其品牌手机的价格。 我需要将这些添加到数据库中。 所以,它应该是这样的
-------------------
AMAZON | IPHONE | 700
-------------------
AMAZON | SAMSUNG | 600
-------------------
WALMART | IPHONE | 699
-------------------
ALIBABA | SONY | 500
-------------------
我需要格式化上面的文本并将其存储在数据库表中。
我试过什么? 我试图拆分多行并创建一个更有可能是 JSON 的字典。但它并没有很好地结束。 但它只需要一根线。 如果还有其他简单的方法,请与我分享。 请在这件事上给予我帮助!
我做了一些假设:
工作代码:
str = """
AMAZON
IPHONE: 700
SAMSUNG: 600
=============
WALMART
IPHONE: 699
===========
ALIBABA
SONY: 500
"""
new_entry = True
print("-------------------")
for line in str.split("\n"):
# assuming first entry is always the vendor name
if not line.strip():
continue
elif new_entry:
vendor = line.strip()
new_entry = False
elif "===" in line:
new_entry = True
else:
product = line.split(":")
print("{} | {} | {}".format(vendor, product[0].strip(), product[1].strip()))
print("-------------------")
Output 是:
-------------------
AMAZON | IPHONE | 700
-------------------
AMAZON | SAMSUNG | 600
-------------------
WALMART | IPHONE | 699
-------------------
ALIBABA | SONY | 500
-------------------
替代方法:供应商名称也可以作为文本行找到,但没有冒号。
@scito 提交的答案已经足够了,但我还是以防万一。 您可以使用正则表达式,以下是一个工作示例:
strng = """
AMAZON
IPHONE: 700
SAMSUNG: 600
=============
WALMART
IPHONE: 699
===========
ALIBABA
SONY: 500
======
"""
multistrng = strng.split("\n") # get each line seperated by \n
import re
market_re = re.compile('([a-zA-Z]+)') # regex to find market name
phone_re = re.compile(r"([a-zA-Z]+):\s(\d+)") # regex to find phone and its price
js = [] # list to hold all data found
for line in multistrng:
phone = phone_re.findall(line) # if line contains phone and its price
if phone:
js[-1].append(phone[0]) # add phone to recently found marketplace
continue
market = market_re.findall(line)
if market: # if line contains market place name
js.append([market[0]])
continue
else:
continue # empty lines ignore
# now you have the data in structured manner, you can print or add it to the database
for market in js:
for product in market[1:]:
print("---------------------")
print("{} | {} | {}".format(market[0], product[0], product[1]))
print("---------------------")
output:
---------------------
AMAZON | IPHONE | 700
---------------------
AMAZON | SAMSUNG | 600
---------------------
WALMART | IPHONE | 699
---------------------
ALIBABA | SONY | 500
---------------------
数据存储在 js 列表中,如果你遍历 js,子列表中的第一个元素是市场,rest 是该市场的产品。
[['AMAZON', ('IPHONE', '700'), ('SAMSUNG', '600')], ['WALMART', ('IPHONE', '699')], ['ALIBABA', ('SONY', '500')]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.