解析包含python 3.x中各种顺序的各种字段的字符串

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

我有一些记录:

records=['Event: Description of some sort of event, sometimes with a: colon 0 Date: 02/05/2008 Time: 9:30 am Location: Room A Result: Description of result 0',
    'Event: Description of event 1 ',
    'Event: Description of some sort of event 2 Date: 06/03/2010 Time: 1:30 pm Location: Room b Result: Description of result 2',
    'Date: 06/03/2010 Time: 2:30 pm  Event: Description of some sort of event 2 Result: Description of result 2 Location: Room b',
    'Date: 06/03/2010 Result: Description of result 3']

我(最终)想要将它们摄取到熊猫数据框中,但我甚至无法弄清楚如何将它们解析成有用的列表或字典。我在做的是:

import re
import pandas as pd
delimeters = ['Event:', 'Date:', 'Time:','Location:', 'Result:']
delimeters = '|'.join(delimeters)
print('without parentheses, I lose my delimeters:')
for record in records:
    print(re.split(delimeters, record))

我很好奇为什么这会在每个列表的开头生成一个空项目。但更重要的是,我想保留分隔符。

我已经看到在单个分隔符周围使用括号的示例将它保留在拆分字符串列表中,但这会产生奇数结果,并带有可能的delmeter列表。我不明白,例如,为什么添加括号会产生Nones - 很想明白这一点!

print('With parentheses things get wierd:')
delimeters = ['(Event:)', '(Date:)', '(Time:)','(Location:)', '(Result:)']
delimeters = '|'.join(delimeters)

for record in records:
    print(re.split(delimeters, record))

理想情况下,我会提取以下内容作为解析记录的输出:

{'Event': ['Description of some sort of event, sometimes with a: colon'], 
 'Date': ['02/05/2008'], 
 'Time': ['1:30 pm'], 
 'Location': ['Room b'],
 'Result': ['Some description of the result, sometimes with a : colon']} # etc

这将使我能够直接传递给数据帧:

pd.DataFrame({'Event': ['Description of some sort of event, sometimes with a: colon'], 
 'Date': ['02/05/2008'], 
 'Time': ['1:30 pm'], 
 'Location': ['Room b'],
 'Result': ['Some description of the result, sometimes with a : colon']} 
)

任何指针或任何步骤的帮助非常感谢。

python-3.x parsing split delimiter
1个回答
1
投票

这是一个不使用正则表达式的解决方案,但它确实涉及嵌套循环:

records = ['Event: Description of some sort of event, sometimes with a: colon 0 Date: 02/05/2008 Time: 9:30 am Location: Room A Result: Description of result 0',
    'Event: Description of event 1 ',
    'Event: Description of some sort of event 2 Date: 06/03/2010 Time: 1:30 pm Location: Room b Result: Description of result 2',
    'Date: 06/03/2010 Time: 2:30 pm  Event: Description of some sort of event 2 Result: Description of result 2 Location: Room b',
    'Date: 06/03/2010 Result: Description of result 3']

delims = ('Event:', 'Date:', 'Time:', 'Location:', 'Result:')

parsed = []

# Iterate records
for record in records:
    # An empty dictionary object
    d = {}
    # Split the record into separate words by spaces
    words = record.split(' ')
    # Iterate the words in the record
    for i in range(len(words)):
        # If this word is one of the delimiters
        if words[i] in delims:
            # Set the key to the delimiter (without a colon)
            key = words[i][:-1]
            # Increment the loop counter to skip to the next item
            i += 1
            # Start with a value of an empty list
            val = []
            # While we are inside the array bounds and the word is not a dilimiter
            while i < len(words) and not words[i] in delims:
                # Add this word to the value
                val.append(words[i])
                # Increment the loop counter to skip to the next item
                i += 1
            # Add the key/value pair to the record dictionary
            d[key] = ' '.join(val)
        # Append the record dictionary to the results
    parsed.append(d)


print(repr(parsed))

我们的想法是将每个记录拆分为单词列表,并检查每个记录是否为分隔符,如果是,则将其设置为键,如果不是,则将该词添加到值中。

输出(漂亮印刷):

[{'Date': '02/05/2008',
  'Event': 'Description of some sort of event, sometimes with a: colon 0',
  'Location': 'Room A',
  'Result': 'Description of result 0',
  'Time': '9:30 am'},
 {'Event': 'Description of event 1 '},
 {'Date': '06/03/2010',
  'Event': 'Description of some sort of event 2',
  'Location': 'Room b',
  'Result': 'Description of result 2',
  'Time': '1:30 pm'},
 {'Date': '06/03/2010',
  'Event': 'Description of some sort of event 2',
  'Location': 'Room b',
  'Result': 'Description of result 2',
  'Time': '2:30 pm '},
 {'Date': '06/03/2010', 'Result': 'Description of result 3'}]
© www.soinside.com 2019 - 2024. All rights reserved.