亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

拆分字符串 python 時出錯,長度為 1,需要 2

拆分字符串 python 時出錯,長度為 1,需要 2

躍然一笑 2022-09-20 17:57:01
我不明白我在這里做錯了什么。這是我的數據:clientSelect : Long Company Name Inc.server1Info : Server1server1Pic : 200330135637030000.jpgserver2Info : Server2server2Pic : 200330140821800000.jpgmodemInfo : AriesmodemPic : 200330140830497000.jpgrouterInfo : RouterrouterPic : 200330140842144000.jpgswitchInfo : Switch1switchGallery_media : 200330140859161000.jpgbuttonSubmit : Submit::end::這當前位于字符串中。它是通過以下方式從共享點提取的lines = folder.get_file('main_equipment_list.txt')lines =  lines.replace(",", "")for row in lines.split(","):這里有些東西要分裂。有位置行是處理一些信息中的一些逗號,這些信息不應該在拆分之前存在。一切都很好,直到它分裂,然后我無法從那里把它變成一個字典。我試過d = dict(s.split(':') for s in lines)print d這讓我很感動  File "testShare.py", line 24, in <module>    d = dict(s.split(':') for s in row)ValueError: dictionary update sequence element #0 has length 1; 2 is required所以想要的是把它變成一個字典。如果我這樣做:for row in lines.split(","):    print(row)我得到:clientSelect : Long Company Name Inc.server1Info : Server1server1Pic : 200330135637030000.jpgserver2Info : Server2server2Pic : 200330140821800000.jpgmodemInfo : AriesmodemPic : 200330140830497000.jpgrouterInfo : RouterrouterPic : 200330140842144000.jpgswitchInfo : Switch1switchGallery_media : 200330140859161000.jpgbuttonSubmit : Submit::end::但是如果我這樣做:for row in lines.split(","):#    print(row)    for s in row:        print(s[0])我在每行上都有一個字符。如果我這樣做:for row in lines.split(","):#    print(row)    for s in row:        print(s[1])我得到一個超出范圍的錯誤。編輯:我回去重新開始。一切都很好,直到我嘗試拆分行。這是有效的方法。lines = folder.get_file('main_equipment_list.txt')lines = lines.rsplit("\n",2)[0]d = {}for line in lines.split("\n"):    if line.strip():        try:            k, v = map(str.strip, line.split(":"))            d[k] = v        except ValueError as ex:            print("on line" % (ex, line))            passprint(d)我認為出錯的是多件事。主要是我對python的不熟悉,以及空格/額外的字符把我搞砸了我得到:['switchGallery_media ', ' 200330140859161000.jpg\r']無論哪種方式,它都有效,我更好地理解了一些事情。感謝您@RoadRunner提供有關顯示錯誤的幫助和提示。
查看完整描述

2 回答

?
POPMUISE

TA貢獻1765條經驗 獲得超5個贊

您會收到此錯誤,因為您正在拆分空的換行符和文件末尾的 。拆分這些行將同時給出 和 。字典是基于的,如果您為字典提供更多或更少的要處理的項目,則會引發異常。::end::['\n']['', '', 'end', '', '']key: valueValueError


您可以在 shell 中輕松重現此異常:


>>> x = ["1:2", "3:4"]

>>> dict(y.split(":") for y in x)

{'1': '2', '3': '4'}

>>> x = ["1:2", "3"]

>>> dict(y.split(":") for y in x)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: dictionary update sequence element #1 has length 1; 2 is required

>>> x = ["1:2:3", "4:5:6"]

>>> dict(y.split(":") for y in x)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ValueError: dictionary update sequence element #0 has length 3; 2 is required

您可以通過剝離空空格或換行符并將拆分的項目解壓縮到由塊保護的元組中來避免這種情況。當我們遇到無效行時,將觸發此異常處理程序。strip()try..catch


with open("data.txt") as f:

    d = {}


    for line in f:


        # avoid empty lines

        if line.strip():

            try:


                # unpack key and value into tuple and strip whitespace

                k, v = map(str.strip, line.split(":"))


                # strip whitespace after splitting

                d[k] = v


            # catch error and print it out

            # use pass to just ignore the error

            except ValueError as ex:

                print("%s occured on line: %s" % (ex, line))

                pass


    print(d)

輸出:


too many values to unpack (expected 2) occured on line: ::end::

{'clientSelect': 'Long Company Name Inc.', 'server1Info': 'Server1', 'server1Pic': '200330135637030000.jpg', 'server2Info': 'Server2', 'server2Pic': '200330140821800000.jpg', 'modemInfo': 'Aries', 'modemPic': '200330140830497000.jpg', 'routerInfo': 'Router', 'routerPic': '200330140842144000.jpg', 'switchInfo': 'Switch1', 'switchGallery_media': '200330140859161000.jpg', 'buttonSubmit': 'Submit'}

請注意我如何打印異常以查看發生了什么。代碼無法解壓縮鍵和值對,因為它有超過 2 個項目要從中解壓縮。代碼仍然創建了字典,但我記錄了異常以查看實際發生了什么。這很容易看到你的代碼出錯的地方。line.split(":")


查看完整回答
反對 回復 2022-09-20
?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

s.split(':')將為您提供一個包含兩個或多個元素的數組。例如["clientSelect ", " Long Company Name Inc."]


您必須從此數組中選擇元素來構造字典,例如


d = {

  splited[0]: splited[1]

}

在我的蟒蛇殼中:


In [1]: s = "clientSelect : Long Company Name Inc."


In [2]: x = s.split(":")


In [3]: x

Out[3]: ['clientSelect ', ' Long Company Name Inc.']


In [4]: d = {x[0]: x[1]}


In [5]: d

Out[5]: {'clientSelect ': ' Long Company Name Inc.'}


查看完整回答
反對 回復 2022-09-20
  • 2 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號