我正在尝试拆分字符串,我得到了ValueError:需要一个以上的值来解压缩
我想我明白了,为什么会发生这个错误,它之所以发生,是因为没有分拆的价值,对吗?
基本上,我有for循环,它从xml返回字符串。
for channel in tree.findall("channel"):
title = channel.find('title').text
channelname,tvguide = title.split("[")
print(channelname,tvguide)当我打印标题时,我有这样的内容:
BeIN体育1HD 07:00 - 07:30 + 106.8分钟自动拨号
BeIN体育2HD ValueError发生在这里?
BeIN体育3HD 23:00 - 02:00 + 1216.8分钟都灵足球对美国帕勒莫-意大利联赛(意甲)
BeIN体育4 4HD ValueError发生在这里?
BeIN体育5HD 05:30-07:15+ 91.8分钟马赛对安格斯-法国甲级联赛2015 - 2016周7
我的问题是,如果有些字符串不包含tvguide,我如何才能修复for循环,以便将所有标题拆分为channelname & tvguide?
例如,在没有电视指南的频道(在本例中,BeIN体育2HD,BeIN体育4HD),它应该使tvguide =“”或类似的内容。
伙计们有什么想法吗?
发布于 2015-09-30 05:03:58
与其分别分配信道名称和tvguide,不如使用split方法返回的列表进行工作。
for channel in tree.findall("channel"):
title = channel.find('title').text
description = title.split("[")
print description这样,您就不必担心通道是否有名称或tvguide,但请确保在通道对象中获得字符串。
as Jon Clements suggested, we still need to figure out if its allowed to access description[1] and as he suggested an elegant way to do is str.partition
for channel in tree.findall("channel"):
title = channel.find('title').text
description = title.partition("[") # you get a tuple with three elements head, separator and tail.
#head is the portion before the separator, separator itself and tail the rest of the portion of the string
print description发布于 2015-09-30 05:08:48
您可以使用简单的if else。
x="BeIN Sports 1HD [07:00 - 07:30] + 106.8 min Auto Mundial"
y="BeIN Sports 2H"
ll=[]
ll.append(x)
ll.append(y)
final = [(i,"") if "[" not in i else i.split("[") for i in ll]
print final输出:[['BeIN Sports 1HD ', '07:00 - 07:30] + 106.8 min Auto Mundial'], ('BeIN Sports 2H', '')]
现在,您可以根据需要轻松地处理列表中的这些元组。
https://stackoverflow.com/questions/32858053
复制相似问题