如何在 python 上使用正则表达式、开关和 trim 来检索文件中的值?

How to use regex, switch and trim on python to retrieve a value in a file?

我有一个格式如下的文件:

Description 10.01.1
;
;     Find the information here
;
University
    National Cantoon University
Status
    National
Administrator visible
    Disable
    *Enable
Start Edu Fair Event
    Event Only
    *Event and invite user
    Event and staff
Permanently Disable
    *No
    Yes
Order
    Year 2021/Jan-Dec(14543043643)

    Year 2022/Jan-Dec(56486565465)

我想获取每个键的值。 例如,我想获得 Status 的值,即 National 如果值有多个,那么我需要获取所有值,例如,我需要获取 Permanently Disable 的值,即 *No and Yes 。我在 PowerShell 中完成了此操作,我使用正则表达式和 trim。但是现在我需要在 Python 中使用它。我是 python 的新人,任何人都可以帮助我,我真的很感激。非常感谢

function info
{
    Param($Path, $Values)
    $name = $false
    switch -regex -file $Path
    {
        $Values{ $name = $true; continue }
        '^\s' { if ($name) { $_.Trim() }}
        '^\S' { if ($name) { return }}
    }
}
with open('text.txt', 'r') as f:
    text = f.read()

d = dict()
key = ""

# iterate line by line
for line in text.split('\n')[1:]:
    # skip empty line
    try:
        # skip header
        if line[0] == ';':
            continue
        # check whether first character is space
        # no --> key
        if not line[0].isspace():
            key = line
            d[key] = list()
            # print("key: ", line)
        # yes --> value
        else:
            # remove space
            d[key].append(line.strip())
            # print("value: ", line.strip())
    except:
        continue

输出:

>>> print(d)
{
 'University': ['National Cantoon University'], 
 'Status': ['National'], 
 'Administrator visible': ['Disable', '*Enable'], 
 'Start Edu Fair Event': ['Event Only', '*Event and invite user', 'Event and staff'], 
 'Permanently Disable': ['*No', 'Yes'], 
 'Order': ['Year 2021/Jan-Dec(14543043643)', 'Year 2022/Jan-Dec(56486565465)']
}