格式化原始字符串Python

问题描述 投票:1回答:5

我有一个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 * - ( previously 02/06/2018 )将设置为等于Date之类的变量,所以当打印print(date)时,02/13/2018 * - ( previously 02/06/2018 )将是输出。

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

for line in message:
     if "DATE:" in line:
          print line
python string format scrape
5个回答
5
投票

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

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'}

3
投票

您可以使用str.splitlines()将字符串拆分为线条。然后遍历这些行并使用regular expression来提取数据,例如:

import re

for line in message.splitlines():
    match = re.match(r'\*DATE: (.*)', line)
    if match:
        date = match.group(1)
        print date

2
投票

For line in message迭代消息中的每个项目:简单来说,消息是一个字符串,其项目是字符(ergo它迭代每个字符)。

Split是解决问题的简单/天真的方法,但只要您的数据不会变得复杂得多,它就可能有效:

使用message.split("\n")在换行符上拆分字符串并迭代它。然后,您可以使用line.strip().strip("*").split(":", maxsplit=1)将键与值分开。第一个strip()删除可能保留的额外空格(例如潜在的“\ r”),第二个删除额外的星号。 maxsplit=1在第一个冒号处停止(如果您的数据有冒号作为标签的一部分,则可能会出现问题)。

我说键/值因为你可能不需要(或想要)动态地将对分配给实际变量,并且可能只是将其存储为dict并根据需要进行查询。

output = dict()
for line in message.split("\n"): ## Split Lines
    key,value = line.strip().split(":",maxsplit=1) ## Remove extra whitespace/* and split at the first colon
    output[key] = value

编辑:我的印象是“日期”只是你的例子,但如果这就是你要找的全部,那么显然只需添加行if key == "DATE"并返回/打印/等值。


0
投票

如果您的数据位于名为datafile.txt的文件中,您可以尝试这样做:

with open('datafile.txt', 'r') as f:
    for line in f:
         if line.startswith("*DATE:"):
            print(line)

0
投票

这个解决方案有效(我认为相当“Pythonic”):

lines = message.split("\n") # Split your message into "lines"
sections = [line.split(": ") for line in lines] # Split lines by the "colon space"
message_dict = {section[0].lstrip(' '): section[1] for section in sections} # Dictionary comprehension to put your keys and values into a dict struct. Also removes leading whitespace from your keys.
© www.soinside.com 2019 - 2024. All rights reserved.