gpt4 book ai didi

python - 格式化原始字符串 Python

转载 作者:太空宇宙 更新时间:2023-11-04 06:59:18 24 4
gpt4 key购买 nike

我在 Python 中有一个原始字符串,它是通过 imap 库检索的。

看起来像这样:

Season: Winter 2017-18
Activity: Basketball - Boys JV
*DATE: 02/13/2018 * - ( previously 02/06/2018 )
Event type: Game
Home/Host: Clear Lake
Opponent: Webster City
*START TIME: 6:15PM CST* - ( previously 4:30PM CST )
Location: Clear Lake High School, 125 N. 20th Street, Clear Lake, IA

废弃每个标签后的数据的最佳方法是什么(标签是DATE:)例如DATE:02/13/2018 * -(以前是02/06/2018 ) 将设置为等于 Date 之类的变量,因此当打印 print(date) 时,02/13/2018 * - (以前是 02/06/2018 ) 将是输出。

我尝试了下面的代码,但它每行打印一个字符。谢谢!

for line in message:
if "DATE:" in line:
print line

最佳答案

您可以使用正则表达式和字典:

import re
s = """
Season: Winter 2017-18
Activity: Basketball - Boys JV
*DATE: 02/13/2018 * - ( previously 02/06/2018 )
Event type: Game
Home/Host: Clear Lake
Opponent: Webster City
*START TIME: 6:15PM CST* - ( previously 4:30PM CST )
Location: Clear Lake High School, 125 N. 20th Street, Clear Lake, IA
"""
final_dict = {(a[1:] if a.startswith('*') else a).strip('\r'):b.strip('\r') for a, b in filter(lambda x:len(x)> 1, [re.split('\:\s', i) for i in filter(None, s.split('\n'))])}

输出:

{'Home/Host': 'Clear Lake', 'Season': 'Winter 2017-18', 'START TIME': '6:15PM CST* - ( previously 4:30PM CST )', 'Location': 'Clear Lake High School, 125 N. 20th Street, Clear Lake, IA', 'Activity': 'Basketball - Boys JV', 'DATE': '02/13/2018 * - ( previously 02/06/2018 )', 'Event type': 'Game', 'Opponent': 'Webster City'}

关于python - 格式化原始字符串 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48024364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com