Python 拆分-值错误:需要超过1个值才能解包
我正在读取一个文本文件,其中包含以下格式的数据:Python 拆分-值错误:需要超过1个值才能解包,python,pandas,Python,Pandas,我正在读取一个文本文件,其中包含以下格式的数据: column : row 以下是一些示例数据: Name of the Property : North Kensington Upcycling Store and Cafe Availability : Now Interest Level : 74 people are looking right now Area : 1,200 sqft Retail Type : No Bar & Restaurant Type :
column : row
以下是一些示例数据:
Name of the Property : North Kensington Upcycling Store and Cafe
Availability : Now
Interest Level : 74 people are looking right now
Area : 1,200 sqft
Retail Type : No
Bar & Restaurant Type : No
我的代码给出了以下错误:
ValueError: need more than 1 value to unpack
在这一行:
k,v = txt_line.split(":")
我的代码:
import pandas
txt_file = r"patty.txt"
txt = open(txt_file, "r")
txt_string = txt.read()
txt_lines = txt_string.split("\n")
txt_dict = {}
for txt_line in txt_lines:
print(txt_line)
k,v = txt_line.split(":")
k = k.strip()
v = v.strip()
if k in txt_dict:
list = txt_dict.get(k)
else:
list = []
list.append(v)
txt_dict[k]=list
print (pandas.DataFrame.from_dict(txt_dict, orient="index"))
如果输入文件的一行为空或缺少冒号,
split
仅返回1个元素,则会出现该错误
为了安全起见,我会进行大小检查以避免异常,并在无法进行解析时打印一条显式消息(我添加了空行跳过以避免在这种情况下崩溃)
Fabre,不,事实上,当我试图复制并粘贴数据时,这是一个错误。我不认为这是问题所在。你能用我的代码修改你的代码,看看会发生什么吗?一定是文件末尾的空行。请等一分钟!它说,无法解析@Jean-François Fabreit的预测是一条空行。我编辑了我的代码以跳过它们。我试图用最少的数据运行它,比如说只有前3行,但我仍然得到错误。我在这里的逻辑有什么错误吗?
if txt_line.strip():
# line is not empty or just blanks
toks = txt_line.split(":")
if len(toks)==2:
# unpack safely
k,v = toks
else:
print("unable to parse {}".format(txt_line))