简体   繁体   English

为什么在python中使用split()方法的值出现值错误?

[英]Why am I getting a value error for values that use the split() method in python?

I'm trying to separate a list of values into keys and values using a dict. 我正在尝试使用字典将值列表分为键和值。 The list if formatted like this: 列表的格式如下:

packagename=version_number
packagename2=version_number2
etc...

Sometimes the version number has special characters, but never an equal sign. 有时版本号带有特殊字符,但绝不包含等号。

dict = {}
with open('file.rtf') as f:
    for line in f.readlines():
        pkg,ver = line.split('=')
        dict[pkg] = ver

print("%s: %s" % (dict[pkg], dict[ver]))    

When I run the code I get the following error: "ValueError: need more than 1 value to unpack" and I'm not sure why. 当我运行代码时,出现以下错误:“ ValueError:需要多个1值才能解压缩”,但我不确定为什么。 I've tried modifying the .rtf file by separating the values on either side of the equal sign with spaces, in case that made a difference. 我试图通过用空格分隔等号两侧的值来修改.rtf文件,以防造成影响。

UPDATE UPDATE

Using a .rtf file was indeed the problem, as pointed out by @tdelaney and others. 正如@tdelaney和其他人指出的那样,使用.rtf文件确实是问题所在。 Code runs smoothly now after converting to plain text. 转换为纯文本后,代码现在可以平稳运行。 Thanks for your help, guys. 伙计们,谢谢您的帮助。

Your input file is in the RTF format, which means it contains formatting codes like this (even if it contains no formatting): 您的输入文件为RTF格式,这意味着它包含这样的格式代码(即使它不包含任何格式):

{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard
packagename=version_number\par
}

This is not the input your program is expecting, and you're probably getting the error on that first line, which contains no = , and therefore splits to one value, giving your error. 这不是您的程序所期望的输入,并且您可能会在第一行收到错误,该错误包含no = ,因此将拆分为一个值,从而给出错误。

Try converting to txt , or write your code to handle RTF. 尝试转换为txt ,或编写代码以处理RTF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM