第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

解析字符串部分

解析字符串部分

慕村225694 2021-03-22 12:09:27
您將使用什么技術(shù)/模塊來解析特定的字符串部分。給定類型的行:field 1: dog        field 2: first        comment: outstandingfield 1: cat        field 2:              comment: some comment about the cat字段名稱始終以冒號結(jié)尾,字段值可以為空白,并且字段之間僅用空格分隔。我只想訪問字段值。我知道如何使用正則表達式來執(zhí)行此操作,但是我敢肯定,使用Python可以執(zhí)行更優(yōu)雅的方法。
查看完整描述

3 回答

?
BIG陽

TA貢獻1859條經(jīng)驗 獲得超6個贊

對我來說,這看起來像是固定寬度的格式。


如果是這樣,您可以這樣做:


data={}

ss=((0,19),(20,41),(42,80))

with open('/tmp/p.txt','r') as f:

    for n,line in enumerate(f):

        fields={}

        for i,j in ss:

            field=line[i:j]

            t=field.split(':')

            fields[t[0].strip()]=t[1].strip()

        data[n]=fields    


print data  

印刷:


{0: {'comment': 'outstanding', 'field 2': 'first', 'field 1': 'dog'}, 1: {'comment': 'some comment about the cat', 'field 2': '', 'field 1': 'cat'}}

如果您想要一個列表:


data=[]

ss=((0,19),(20,41),(42,80))

with open('/tmp/p.txt','r') as f:

    for n,line in enumerate(f):

        fields={}

        for i,j in ss:

            field=line[i:j]

            t=field.split(':')

            fields[t[0].strip()]=t[1].strip()

        data.append(fields)   

無論哪種情況,您都可以訪問:


>>> data[0]['comment']

'outstanding'     


查看完整回答
反對 回復 2021-03-27
?
蠱毒傳說

TA貢獻1895條經(jīng)驗 獲得超3個贊

像這樣的東西:


>>> with open("abc") as f:

    lis = []

    for line in f:

        lis.append(dict( map(str.strip, x.split(":")) for x in line.split(" "*8)))

...         

>>> lis

[{'comment': 'outstanding', 'field 2': 'first', 'field 1': 'dog'},

 {'comment': 'some comment about the cat', 'field 2': '', 'field 1': 'cat'}

]


>>> lis[0]['comment']    #access 'comment' field on line 1

'outstanding' 

>>> lis[1]['field 2']    # access 'field 2' on line 2

''


查看完整回答
反對 回復 2021-03-27
?
呼啦一陣風

TA貢獻1802條經(jīng)驗 獲得超6個贊

另一種選擇是使用csv模塊。


假設(shè)字段之間有一個制表符分隔符:


import StringIO

import csv


input_data = StringIO.StringIO("""field 1: dog  field 2: first  comment: outstanding

field 1: cat    field 2:    comment: some comment about the cat""")


data = []

for row in csv.reader(input_data, delimiter="\t"):

    line = {}

    for item in row:

        value = item.split(":")

        line[value[0]] = value[1].strip()


    data.append(line)


print data

印刷


[{'comment': 'outstanding', 'field 2': 'first', 'field 1': 'dog'}, {'comment': 'some comment about the cat', 'field 2': '', 'field 1': 'cat'}]


查看完整回答
反對 回復 2021-03-27
  • 3 回答
  • 0 關(guān)注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號