拆分字符串 python 时出错,长度为 1,需要 2

我不明白我在这里做错了什么。


这是我的数据:


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

这当前位于字符串中。它是通过以下方式从共享点提取的


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 : 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的不熟悉,以及空格/额外的字符把我搞砸了


我得到:


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

无论哪种方式,它都有效,我更好地理解了一些事情。感谢您@RoadRunner提供有关显示错误的帮助和提示。


跃然一笑
浏览 153回答 2
2回答

POPMUISE

您会收到此错误,因为您正在拆分空的换行符和文件末尾的 。拆分这些行将同时给出 和 。字典是基于的,如果您为字典提供更多或更少的要处理的项目,则会引发异常。::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):&nbsp; 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):&nbsp; File "<stdin>", line 1, in <module>ValueError: dictionary update sequence element #0 has length 3; 2 is required您可以通过剥离空空格或换行符并将拆分的项目解压缩到由块保护的元组中来避免这种情况。当我们遇到无效行时,将触发此异常处理程序。strip()try..catchwith open("data.txt") as f:&nbsp; &nbsp; d = {}&nbsp; &nbsp; for line in f:&nbsp; &nbsp; &nbsp; &nbsp; # avoid empty lines&nbsp; &nbsp; &nbsp; &nbsp; if line.strip():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # unpack key and value into tuple and strip whitespace&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; k, v = map(str.strip, line.split(":"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # strip whitespace after splitting&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d[k] = v&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # catch error and print it out&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # use pass to just ignore the error&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; except ValueError as ex:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("%s occured on line: %s" % (ex, line))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; &nbsp; 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(":")

绝地无双

s.split(':')将为您提供一个包含两个或多个元素的数组。例如["clientSelect ", " Long Company Name Inc."]您必须从此数组中选择元素来构造字典,例如d = {&nbsp; splited[0]: splited[1]}在我的蟒蛇壳中:In [1]: s = "clientSelect : Long Company Name Inc."In [2]: x = s.split(":")In [3]: xOut[3]: ['clientSelect ', ' Long Company Name Inc.']In [4]: d = {x[0]: x[1]}In [5]: dOut[5]: {'clientSelect ': ' Long Company Name Inc.'}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python