我有一個這種格式的檔案:
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
which isNational
的值如果值有多個,那么我需要獲取所有值,例如,我需要獲取Permanently Disable
which is的值*No and Yes
。我已經在 PowerShell 中完成了這個,我使用了正則運算式和修剪。但現在我需要在 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 }}
}
}
uj5u.com熱心網友回復:
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)'] }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/382310.html