在本文中,您将会了解到关于PythonValueError:太多值无法解压的新资讯,同时我们还将为您解释python无法处理特别大的数据文件的相关在本文中,我们将带你探索PythonValueErro
在本文中,您将会了解到关于Python ValueError:太多值无法解压的新资讯,同时我们还将为您解释python无法处理特别大的数据文件的相关在本文中,我们将带你探索Python ValueError:太多值无法解压的奥秘,分析python无法处理特别大的数据文件的特点,并给出一些关于Django python ValueError:没有足够的值要解压(预期为2,得到1)、OpenCV python:ValueError:太多值无法解包、Python json.loads显示ValueError:额外数据、python mysql ValueError:无法处理参数的实用技巧。
本文目录一览:- Python ValueError:太多值无法解压(python无法处理特别大的数据文件)
- Django python ValueError:没有足够的值要解压(预期为2,得到1)
- OpenCV python:ValueError:太多值无法解包
- Python json.loads显示ValueError:额外数据
- python mysql ValueError:无法处理参数
Python ValueError:太多值无法解压(python无法处理特别大的数据文件)
我从这段代码中得到该异常:
class Transaction: def __init__ (self): self.materials = {} def add_material (self, m): self.materials[m.type + m.purity] = m def serialize (self): ser_str = ''transaction_start\n'' for k, m in self.materials: ser_str += m.serialize () sert += ''transaction_end\n'' return ser_str
这for
行是引发异常的行。该m
s为Material
对象。有人有什么想法吗?
答案1
小编典典self.materials
是一个dict
,默认情况下,您仅迭代键(字符串)。
由于self.materials
具有两个以上的键*,因此无法将它们解压到tuple
“k,m
”中,因此引发了异常。ValueError
在Python 2. x中
,要遍历键和值(tuple
“k,m
”),我们使用self.materials.iteritems()
。
但是,由于无论如何都将键扔掉了,因此还可以简单地遍历字典的值:
for m in self.materials.itervalues():
在Python 3. x中 ,preferreddict.values()
(返回字典视图对象):
for m in self.materials.values():
Django python ValueError:没有足够的值要解压(预期为2,得到1)
第3行读取
pairs = [reports,daily]
这为您提供了一个包含两个列表的列表。如果将其循环,它将循环两次,首先为您提供报告列表,然后为您提供每日列表。试试这个:
for item in pairs:
print(item)
print(type(item))
这应该使问题显而易见。解决方案是用以下代码替换第3行:
pairs = zip(reports,daily)
这将为您提供一对可重复的对,其中每个对都有一份报告,并且其中有一天。
OpenCV python:ValueError:太多值无法解包
运行脚本答案时,出现以下错误:
Traceback (most recent call last): File "skinimagecontour.py", line 13, in <module> contours, _ = cv2.findContours(skin_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)ValueError: too many values to unpack
编码:
import sysimport numpyimport cv2im = cv2.imread(''Photos/test.jpg'')im_ycrcb = cv2.cvtColor(im, cv2.COLOR_BGR2YCR_CB)skin_ycrcb_mint = numpy.array((0, 133, 77))skin_ycrcb_maxt = numpy.array((255, 173, 127))skin_ycrcb = cv2.inRange(im_ycrcb, skin_ycrcb_mint, skin_ycrcb_maxt)cv2.imwrite(''Photos/output2.jpg'', skin_ycrcb) # Second imagecontours, _ = cv2.findContours(skin_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)for i, c in enumerate(contours): area = cv2.contourArea(c) if area > 1000: cv2.drawContours(im, contours, i, (255, 0, 0), 3)cv2.imwrite(''Photos/output3.jpg'', im)
任何帮助表示赞赏!
答案1
小编典典我从OpenCV StackExchange网站获得了答案。回答
答案:
我敢打赌,您正在使用当前的OpenCV的master分支:此处的return语句已更改,请参阅http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=findcontours。
因此,将相应的行更改为:
_, contours, _= cv2.findContours(skin_ycrcb, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
或者:由于当前干线仍然不稳定,您可能还会遇到其他问题,因此您可能需要使用OpenCV的当前稳定版本2.4.9。
Python json.loads显示ValueError:额外数据
我正在从JSON文件“ new.json”
中获取一些数据,我想过滤一些数据并将其存储到新的JSON文件中。这是我的代码:
import jsonwith open(''new.json'') as infile: data = json.load(infile)for item in data: iden = item.get["id"] a = item.get["a"] b = item.get["b"] c = item.get["c"] if c == ''XYZ'' or "XYZ" in data["text"]: filename = ''abc.json'' try: outfile = open(filename,''ab'') except: outfile = open(filename,''wb'') obj_json={} obj_json["ID"] = iden obj_json["VAL_A"] = a obj_json["VAL_B"] = b
我收到一个错误,回溯是:
File "rtfav.py", line 3, in <module> data = json.load(infile) File "/usr/lib64/python2.7/json/__init__.py", line 278, in load **kw) File "/usr/lib64/python2.7/json/__init__.py", line 326, in loads return _default_decoder.decode(s) File "/usr/lib64/python2.7/json/decoder.py", line 369, in decode raise ValueError(errmsg("Extra data", s, end, len(s)))ValueError: Extra data: line 88 column 2 - line 50607 column 2 (char 3077 - 1868399)
有人能帮我吗?
这是new.json中数据的示例,文件中还有约1500种这样的词典
{ "contributors": null, "truncated": false, "text": "@HomeShop18 #DreamJob to professional rafter", "in_reply_to_status_id": null, "id": 421584490452893696, "favorite_count": 0, "source": "<a href=\"https://mobile.twitter.com\" rel=\"nofollow\">Mobile Web (M2)</a>", "retweeted": false, "coordinates": null, "entities": { "symbols": [], "user_mentions": [ { "id": 183093247, "indices": [ 0, 11 ], "id_str": "183093247", "screen_name": "HomeShop18", "name": "HomeShop18" } ], "hashtags": [ { "indices": [ 12, 21 ], "text": "DreamJob" } ], "urls": [] }, "in_reply_to_screen_name": "HomeShop18", "id_str": "421584490452893696", "retweet_count": 0, "in_reply_to_user_id": 183093247, "favorited": false, "user": { "follow_request_sent": null, "profile_use_background_image": true, "default_profile_image": false, "id": 2254546045, "verified": false, "profile_image_url_https": "https://pbs.twimg.com/profile_images/413952088880594944/rcdr59OY_normal.jpeg", "profile_sidebar_fill_color": "171106", "profile_text_color": "8A7302", "followers_count": 87, "profile_sidebar_border_color": "BCB302", "id_str": "2254546045", "profile_background_color": "0F0A02", "listed_count": 1, "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png", "utc_offset": null, "statuses_count": 9793, "description": "Rafter. Rafting is what I do. Me aur mera Tablet. Technocrat of Future", "friends_count": 231, "location": "", "profile_link_color": "473623", "profile_image_url": "http://pbs.twimg.com/profile_images/413952088880594944/rcdr59OY_normal.jpeg", "following": null, "geo_enabled": false, "profile_banner_url": "https://pbs.twimg.com/profile_banners/2254546045/1388065343", "profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png", "name": "Jayy", "lang": "en", "profile_background_tile": false, "favourites_count": 41, "screen_name": "JzayyPsingh", "notifications": null, "url": null, "created_at": "Fri Dec 20 05:46:00 +0000 2013", "contributors_enabled": false, "time_zone": null, "protected": false, "default_profile": false, "is_translator": false }, "geo": null, "in_reply_to_user_id_str": "183093247", "lang": "en", "created_at": "Fri Jan 10 10:09:09 +0000 2014", "filter_level": "medium", "in_reply_to_status_id_str": null, "place": null}
答案1
小编典典如你在以下示例中看到的,json.loads
(和json.load
)不会解码多个json
对象。
>>> json.loads(''{}''){}>>> json.loads(''{}{}'') # == json.loads(json.dumps({}) + json.dumps({}))Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\json\__init__.py", line 338, in loads return _default_decoder.decode(s) File "C:\Python27\lib\json\decoder.py", line 368, in decode raise ValueError(errmsg("Extra data", s, end, len(s)))ValueError: Extra data: line 1 column 3 - line 1 column 5 (char 2 - 4)
如果要转储多个字典,请将它们包装在列表中,然后转储列表(而不是多次转储字典)
>>> dict1 = {}>>> dict2 = {}>>> json.dumps([dict1, dict2])''[{}, {}]''>>> json.loads(json.dumps([dict1, dict2]))[{}, {}]
python mysql ValueError:无法处理参数
如何解决python mysql ValueError:无法处理参数?
我有一些 Python 代码,可以将一列添加到表中,然后遍历列表并将每个值添加到该列中。它添加了列,但不添加任何值。它给了我错误 ValueError: 无法处理参数,但是当我在 MysqL 控制台中键入相同的命令时,它工作得很好。以下是我的代码和错误消息的相关部分。让我知道是否有任何明显的错误。请和谢谢。
mycursor = mydb.cursor()
colname=input()
que="ALTER TABLE timestamps ADD {} TIMESTAMP(6) ".format(colname)
mycursor.execute(que)
print(que)
for i in range(len(res)):
val = res[i]
print(val)
sql = "INSERT INTO timestamps ({}) VALUES (''{}'') ".format(colname,val)
print(sql)
mycursor.execute(sql,val)
mydb.commit()
asdf
ALTER TABLE timestamps ADD asdf TIMESTAMP(6)
2021-05-23 02:32:20.660
INSERT INTO timestamps (asdf) VALUES (''2021-05-23 02:32:20.660'')
Traceback (most recent call last):
File "upload_onsets.py",line 89,in <module>
mycursor.execute(sql,val)
File "/home/ubuntu2004/.local/lib/python3.8/site-packages/MysqL/connector/cursor_cext.py",line 257,in execute
prepared = self._cnx.prepare_for_MysqL(params)
File "/home/ubuntu2004/.local/lib/python3.8/site-packages/MysqL/connector/connection_cext.py",line 651,in prepare_for_MysqL
raise ValueError("Could not process parameters")
ValueError: Could not process parameters
解决方法
由于您在 cursor.execute()
中提供值,因此您需要将占位符放入 SQL,而不是将值格式化。
cursor.execute()
的第二个参数应该是一个元组,而不是单个值。
无需在循环内分配 sql
,因为它不会改变。
sql = "INSERT INTO timestamps ({}) VALUES (%s) ".format(colname)
print(sql)
for i in range(len(res)):
val = res[i]
print(val)
mycursor.execute(sql,(val,))
但是,您可以使用 executemany()
而不是循环来更有效地执行此操作。
sql = "INSERT INTO timestamps ({}) VALUES (%s) ".format(colname)
vals = [(val,) for val in res]
mycursor.executemany(sql,vals)
这会将所有插入合并到一个带有多个 VALUES
列表的查询中。
关于Python ValueError:太多值无法解压和python无法处理特别大的数据文件的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Django python ValueError:没有足够的值要解压(预期为2,得到1)、OpenCV python:ValueError:太多值无法解包、Python json.loads显示ValueError:额外数据、python mysql ValueError:无法处理参数等相关知识的信息别忘了在本站进行查找喔。
本文标签: