エラー分割文字列のpythonは、長さ1、2が必要とされています

TheEditor:

私はここで間違ってやっているかを把握することはできません。

ここに私のデータは次のとおりです。

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

::end::

これは文字列中です。これは、SharePointを経由してから引き出しています

lines = folder.get_file('main_equipment_list.txt')
lines =  lines.replace(",", "")

for row in lines.split(","):

ここで何かTO SPLIT。

Thereplaceラインが分割前に存在しないはずの情報の一部にいくつかのカンマに対処することです。

すべてが、私はそこから辞書にそれを得ることができないその分割までの罰金です。

私はもう試した

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 : 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

::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))
            pass

print(d)

私が考えることは、複数のものを間違ってたつもりでした。主に私のpythonと不慣れ、および空白/余分な文字が私をめちゃくちゃ

私はいくつかのテストをしていました。私はこれを使用する場合:

lines = lines.rsplit("\n",2)[0]

for line in lines.split("\n"):
    if line.strip():
        try:
            x = line.split(":", 1)                                                                                                                                  
            print(x)

        except ValueError as ex:
            print("on line" % (ex, line))
            pass

私が取得します:

['switchGallery_media ', ' 200330140859161000.jpg\r']

いずれにせよ、それは動作し、私はより良いいくつかのことを理解しています。エラーを示すのヘルプやヒントのためにあなたを@RoadRunnerありがとうございます。

ロードランナー:

あなたは空の改行を分割しているため、このエラーを取得している::end::ファイルの最後に。分割これらの行が得られます両方['\n']['', '', 'end', '', '']辞書がされkey: value基づいており、発生しますValueError、あなたはそれをプロセスに多かれ少なかれアイテムを与える場合は、例外を。

あなたは、シェルで簡単にこの例外を再現することができます。

>>> 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(":")コードはまだ辞書を作成したが、私は本当に何が起こっているか確認するために、例外をログに記録しました。これはあなたのコードが間違って起こっている場所を確認するために便利です。

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=377664&siteId=1