python错误:ValueError: No JSON object could be decoded

#-*- coding:utf-8 -*-

import requests

from operator import itemgetter

执行API调用并存储响应

url = 'http://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
print("Status code:", r.status_code)

处理有关每篇文章的信息

submission_ids = r.json()
submission_dicts = []
for submission_id in submission_ids[:30]:
# 对于每篇文章,都执行一个API调用
url = ('http://hacker-news.firebaseio.com/v0/item/' + str(submission_id) + '.json')
submission_r = requesets.get(url)
print(submisssion_r.status_code)
reponse_dict = submission_r.json()

submission_dict = {
    'title': resopnse_dict['title'],
    'link': 'http://news.ycombinator.com/item?id=' + str(submission_id),
    'comments': response_dict.get('descendants', 0)
    }
submission_dicts.append(submission_dict)

submission_dicts = sorted(submission_dicts, key=itemgetter('comments'), recerse=Ture)

for submission_dict in submission_dicts:
print("/nTitle:", submission_dict['title'])
print("Discussion link:", submission_dict['link'])
print("Comeents", submission_dict['comments'])

1个回答

代码里有输入错误,
而且你要获取的url地址,取不到东西

slevenxulianjie
slevenxulianjie 因为取不到json,所以后面的代码也没调试
大约一年之前 回复
ty540583827
ty540583827 回复slevenxulianjie: 那就是这个url有问题么?
大约一年之前 回复
slevenxulianjie
slevenxulianjie 获取时报错:Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。')
大约一年之前 回复
ty540583827
ty540583827 那个url能取到东西呀?!不能么?
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
python json解析出现No JSON object could be decoded的报错

源代码:#coding:utf-8 import requests import re import json url="http://www.newrank.cn/public/info/list.js?t=1461063208.68" user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = { 'User-Agent' : user_agent } jscontent=requests.get("http://www.newrank.cn/public/info/list.js?t=1461063208.68",headers=headers).content jsdict=json.loads(jscontent) 错误信息:Traceback (most recent call last): File "D:/Python/JetBrains PyCharm 5.0.4/PyCharm 5.0.4/Myproject/test1/test2.py", line 10, in <module> jsdict=json.loads(jscontent) File "D:\Python\lib\json\__init__.py", line 339, in loads return _default_decoder.decode(s) File "D:\Python\lib\json\decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "D:\Python\lib\json\decoder.py", line 382, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded 是因为json的bom头问题吗,我也尝试过一些网上的去除bom头的办法,不过都不管用,还望指点,非常头疼,谢谢!

爬虫过程中遇到报错:ValueError: can only parse strings

源代码如下: import requests import json from requests.exceptions import RequestException import time from lxml import etree def get_one_page(url): try: headers = { 'User-Agent': 'Mozilla/5.0(Macintosh;Intel Mac OS X 10_13_3) AppleWebKit/537.36(KHTML,like Gecko) Chorme/65.0.3325.162 Safari/537.36' } response = requests.get(url,headers = headers) if response.status_code == 200: return response.text return None except RequestException: return None def parse_one_page(html): html_coner = etree.HTML(html) pattern = html_coner.xpath('//div[@id="container"]/div[@id="main"/div[@class = "ywnr_box"]//a/text()') return pattern def write_to_file(content): with open('results.txt','a',encoding='utf-8') as f: f.write(json.dumps(content,ensure_ascii=False)+'\n') def main(offset): url = 'http://www.cdpf.org.cn/yw/index_'+str(offset)+'.shtml' html = get_one_page(url) for item in parse_one_page(html): print(item) write_to_file(item) if __name__ == '__main__': for i in range(6): main(offset=i*10) time.sleep(1) 请问各位大佬到底是哪里出了错??

python调用cv2.findContours时报错:ValueError: not enough values to unpack (expected 3, got 2)

完整代码如下: ``` import cv2 import numpy as np img = np.zeros((200, 200), dtype=np.uint8) img[50:150, 50:150] = 255 ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) img = cv2.drawContours(color, contours, -1, (0,255,0), 2) cv2.imshow("contours", color) cv2.waitKey() cv2.destroyAllWindows() ``` 但是cv2.findContours报如下错误: ValueError: not enough values to unpack (expected 3, got 2) python版本为3.6,opencv为4.0.0

如何使用python中的HTTPrequests库从我的php本地服务器返回json数据?

<div class="post-text" itemprop="text"> <p>My Python script:</p> <pre><code>import requests import json location = '127.0.0.1' port = 8000 # Setup the REST API URL string apiString = 'http://' + location + ':' + str(port) + '/edsa-Python/Matrix_mult_dynamic/run_python.php' print apiString #Make the REST API Request resp = requests.get(apiString) print resp.text # print resp.encoding # Get the JSON that is returned if resp.status_code == requests.codes.ok: the_json = resp.json() #print the_json </code></pre> <p>Error: I get an error saying that No JSON object could be decoded. Below is the error that I get when I run the python script in the command prompt:</p> <pre><code>http://127.0.0.1:8000/edsa-Python/Matrix_mult_dynamic/run_python.php Traceback (most recent call last): File "client_python.py", line 25, in &lt;module&gt; the_json = resp.json() File "C:\Python27\lib\site-packages equests-2.12.0-py2.7.egg equests\models.py", line 841, in json return complexjson.loads(self.text, **kwargs) File "C:\Python27\lib\json\__init__.py", line 339, in loads return _default_decoder.decode(s) File "C:\Python27\lib\json\decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded </code></pre> </div>

TypeError: len() of unsized object

Traceback (most recent call last): File "<stdin>", line 1, in <module> File "E:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile execfile(filename, namespace) File "E:\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 88, in execfile exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace) File "F:/05paper/graduation paper/Gmm/expertInstitution.py", line 27, in <module> main() File "F:/05paper/graduation paper/Gmm/expertInstitution.py", line 23, in main scholarInstition() File "F:/05paper/graduation paper/Gmm/expertInstitution.py", line 17, in scholarInstition if scholarData.iloc[j,0]==paperId.iloc[i]: File "E:\Anaconda3\lib\site-packages\pandas\core\ops.py", line 739, in wrapper if len(self) != len(other): TypeError: len() of unsized object

ValueError: shape mismatch: objects cannot be broadcast to a single shape

在使用matplotlib进行动态绘图时发生如题错误 源码: ``` import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager import numpy as np import csv f=open("C:/Users/jyz_1/Desktop/datamodi.csv","r") y_list=[] t0=eval(input("时间间隔:")) POINTS = 10*t0+1 y_list = [0] * POINTS indx = 0 fig, ax = plt.subplots() ax.set_ylim([0,40]) ax.set_xlim([0, POINTS]) ax.set_autoscale_on(False) ax.set_xticks(range(0, 10*t0, t0)) ax.set_yticks(range(0,40,5)) ax.grid(True) line_y, = ax.plot(range(POINTS), y_list, label='y output', color='cornflowerblue') ax.legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10)) def y_output(ax): global indx, y_list, line_y if indx == 20: indx = 0 indx += 1 f=open("C:/Users/jyz_1/Desktop/datamodi.csv","r") y_list=[] reader=csv.reader(f) for low in reader: for y in low: y_list=np.append(y_list,eval(y)) line_y.set_ydata(y_list) ax.draw_artist(line_y) ax.figure.canvas.draw() timer = fig.canvas.new_timer(interval=100) timer.add_callback(y_output, ax) timer.start() plt.show() ``` 报错: > Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__ return self.func(*args) File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 804, in callit func(*args) File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\backends\_backend_tk.py", line 114, in _on_timer TimerBase._on_timer(self) File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\backend_bases.py", line 1187, in _on_timer ret = func(*args, **kwargs) File "C:\Users\jyz_1\Desktop\sensor_ver1.py", line 32, in y_output ax.draw_artist(line_y) File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\axes\_base.py", line 2644, in draw_artist a.draw(self.figure._cachedRenderer) File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\artist.py", line 38, in draw_wrapper return draw(artist, renderer, *args, **kwargs) File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\lines.py", line 759, in draw self.recache() File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\matplotlib\lines.py", line 679, in recache self._xy = np.column_stack(np.broadcast_arrays(x, y)).astype(float) File "<__array_function__ internals>", line 5, in broadcast_arrays File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\stride_tricks.py", line 264, in broadcast_arrays shape = _broadcast_shape(*args) File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\numpy\lib\stride_tricks.py", line 191, in _broadcast_shape b = np.broadcast(*args[:32]) ValueError: shape mismatch: objects cannot be broadcast to a single shape

关于celery启动任务时报错Thread 'ResultHandler' crashed: ValueError('invalid file descriptor 13',)

我使用celery定时器执行任务,可启动时会出现这个错误 ``` [2019-10-22 09:13:30,334: INFO/MainProcess] Connected to redis://127.0.0.1:6379/14 [2019-10-22 09:13:30,361: INFO/MainProcess] mingle: searching for neighbors [2019-10-22 09:13:30,532: INFO/Beat] beat: Starting... [2019-10-22 09:13:31,072: ERROR/Beat] Thread 'ResultHandler' crashed: ValueError('invalid file descriptor 13',) Traceback (most recent call last): File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/pool.py", line 899, in body for _ in self._process_result(1.0): # blocking File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/pool.py", line 864, in _process_result ready, task = poll(timeout) File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/pool.py", line 1370, in _poll_result if self._outqueue._reader.poll(timeout): File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 285, in poll return self._poll(timeout) File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 463, in _poll r = wait([self], timeout) File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 996, in wait return _poll(object_list, timeout) File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 976, in _poll raise ValueError('invalid file descriptor %i' % fd) ValueError: invalid file descriptor 13 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/pool.py", line 504, in run return self.body() File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/pool.py", line 904, in body self.finish_at_shutdown() File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/pool.py", line 953, in finish_at_shutdown if not outqueue._reader.poll(): File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 285, in poll return self._poll(timeout) File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 463, in _poll r = wait([self], timeout) File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 991, in wait return _poll(object_list, 0) File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 976, in _poll raise ValueError('invalid file descriptor %i' % fd) ValueError: invalid file descriptor 13 [2019-10-22 09:13:31,408: INFO/MainProcess] mingle: all alone [2019-10-22 09:13:31,423: INFO/MainProcess] celery@iZwz9h41nalpsqzz57x4tmZ ready. ``` 重启几次这个错误就不会出现,但运行一段时间后再次从定时器发布任务时还会出现该错误导致任务执行失败 ``` [2019-10-22 07:00:00,000: INFO/Beat] Scheduler: Sending due task monitoring_auto_run (run.monitoring_auto_run) [2019-10-22 07:00:00,008: INFO/MainProcess] Received task: run.monitoring_auto_run[469ee195-3e1a-4bf0-a7cb-783232e8d0bc] [2019-10-22 07:00:00,105: ERROR/ForkPoolWorker-11] Thread 'ResultHandler' crashed: ValueError('invalid file descriptor 14',) Traceback (most recent call last): File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/pool.py", line 504, in run return self.body() File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/pool.py", line 899, in body for _ in self._process_result(1.0): # blocking File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/pool.py", line 864, in _process_result ready, task = poll(timeout) File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/pool.py", line 1370, in _poll_result if self._outqueue._reader.poll(timeout): File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 285, in poll return self._poll(timeout) File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 463, in _poll r = wait([self], timeout) File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 996, in wait return _poll(object_list, timeout) File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/connection.py", line 976, in _poll raise ValueError('invalid file descriptor %i' % fd) ValueError: invalid file descriptor 14 [2019-10-22 07:00:00,768: ERROR/MainProcess] Process 'ForkPoolWorker-11' pid:15068 exited with 'exitcode 1' [2019-10-22 07:00:11,186: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: exitcode 1.',) Traceback (most recent call last): File "/pyenvs/spider/lib64/python3.6/site-packages/billiard/pool.py", line 1267, in mark_as_worker_lost human_status(exitcode)), billiard.exceptions.WorkerLostError: Worker exited prematurely: exitcode 1. ```

python运行时出现ValueError: Invalid file name (invalid file name)

相关程序如下 ``` parser = argparse.ArgumentParser(description='evaluate.py') parser.add_argument('INPUT', help='path to input image') parser.add_argument('REF', default="", nargs="?", help='path to reference image, if omitted NR IQA is assumed') parser.add_argument('--model', '-m', default='', help='path to the trained model') parser.add_argument('--top', choices=('patchwise', 'weighted'), default='weighted', help='top layer and loss definition') parser.add_argument('--gpu', '-g', default=0, type=int, help='GPU ID') args = parser.parse_args() ``` 我在运行 ``` python evaluate.py D:\PyCharm 2019.3.3\test-code\deepIQA-master\img.jpg ``` 后提示我 ``` Traceback (most recent call last): File "D:/PyCharm 2019.3.3/test-code/deepIQA-master/evaluate.py", line 75, in <module> serializers.load_hdf5(args.model, model) File "D:\PyCharm 2019.3.3\lib\site-packages\chainer\serializers\hdf5.py", line 195, in load_hdf5 with h5py.File(filename, 'r') as f: File "D:\PyCharm 2019.3.3\lib\site-packages\h5py\_hl\files.py", line 408, in __init__ swmr=swmr) File "D:\PyCharm 2019.3.3\lib\site-packages\h5py\_hl\files.py", line 173, in make_fid fid = h5f.open(name, flags, fapl=fapl) File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper File "h5py\h5f.pyx", line 88, in h5py.h5f.open ValueError: Invalid file name (invalid file name) ``` 是我的图片路径不对么?

关于object detection运行视频检测代码出现报错:ValueError:assignment destination is read-only

我参考博主 withzheng的博客:https://blog.csdn.net/xiaoxiao123jun/article/details/76605928 在视频物体识别的部分中,我用的是Anaconda自带的spyder(python3.6)来运行他给的视频检测代码,出现了如下报错,![图片说明](https://img-ask.csdn.net/upload/201904/20/1555752185_448895.jpg) 具体报错: Moviepy - Building video video1_out.mp4. Moviepy - Writing video video1_out.mp4 t: 7%|▋ | 7/96 [00:40<09:17, 6.26s/it, now=None]Traceback (most recent call last): File "", line 1, in runfile('C:/models-master1/research/object_detection/object_detection_tutorial (1).py', wdir='C:/models-master1/research/object_detection') File "C:\Users\Administrator\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\Users\Administrator\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(),filename,'exec'), namespace) File "C:/models-master1/research/object_detection/object_detection_tutorial (1).py", line 273, in white_clip.write_videofile(white_output, audio=False) File "", line 2, in write_videofile File "C:\Users\Administrator\Anaconda3\lib\site-packages\moviepy\decorators.py", line 54, in requires_duration return f(clip, *a, **k) File "", line 2, in write_videofile File "C:\Users\Administrator\Anaconda3\lib\site-packages\moviepy\decorators.py", line 137, in use_clip_fps_by_default return f(clip, *new_a, **new_kw) File "", line 2, in write_videofile File "C:\Users\Administrator\Anaconda3\lib\site-packages\moviepy\decorators.py", line 22, in convert_masks_to_RGB return f(clip, *a, **k) File "C:\Users\Administrator\Anaconda3\lib\site-packages\moviepy\video\VideoClip.py", line 326, in write_videofile logger=logger) File "C:\Users\Administrator\Anaconda3\lib\site-packages\moviepy\video\io\ffmpeg_writer.py", line 216, in ffmpeg_write_video fps=fps, dtype="uint8"): File "C:\Users\Administrator\Anaconda3\lib\site-packages\moviepy\Clip.py", line 475, in iter_frames frame = self.get_frame(t) File "", line 2, in get_frame File "C:\Users\Administrator\Anaconda3\lib\site-packages\moviepy\decorators.py", line 89, in wrapper return f(*new_a, **new_kw) File "C:\Users\Administrator\Anaconda3\lib\site-packages\moviepy\Clip.py", line 95, in get_frame return self.make_frame(t) File "C:\Users\Administrator\Anaconda3\lib\site-packages\moviepy\Clip.py", line 138, in newclip = self.set_make_frame(lambda t: fun(self.get_frame, t)) File "C:\Users\Administrator\Anaconda3\lib\site-packages\moviepy\video\VideoClip.py", line 511, in return self.fl(lambda gf, t: image_func(gf(t)), apply_to) File "C:/models-master1/research/object_detection/object_detection_tutorial (1).py", line 267, in process_image image_process=detect_objects(image,sess,detection_graph) File "C:/models-master1/research/object_detection/object_detection_tutorial (1).py", line 258, in detect_objects line_thickness=8) File "C:\models-master1\research\object_detection\utils\visualization_utils.py", line 743, in visualize_boxes_and_labels_on_image_array use_normalized_coordinates=use_normalized_coordinates) File "C:\models-master1\research\object_detection\utils\visualization_utils.py", line 129, in draw_bounding_box_on_image_array np.copyto(image, np.array(image_pil)) ValueError: assignment destination is read-only 想问问各位大神有遇到过类似的问题吗。。如何解决?

在使用KNN算法的时候报错:ValueError: query data dimension must match training data dimension

在使用KNN算法的过程中产生了错误 下图为代码: ![图片说明](https://img-ask.csdn.net/upload/202004/15/1586931262_835281.png) 报错: ![图片说明](https://img-ask.csdn.net/upload/202004/15/1586931388_462897.png) ![图片说明](https://img-ask.csdn.net/upload/202004/15/1586931408_33765.png) 描述的错误信息是:值错误:查询数据维度必须与培训数据维度匹配 但我也不知道该怎么把数据维度匹配起来啊 求大佬帮帮忙,我在网上找了好久都没有解决的办法

反归一化时报错ValueError: operands could not be broadcast together with shapes

在使用scaler.inverse_transform(y_test)进行反归一化时,报错ValueError: operands could not be broadcast together with shapes (984,2) (4,)(984,2),我断调试了一下,在这个位置报错:![图片说明](https://img-ask.csdn.net/upload/202005/14/1589426709_978169.png)

Mongo使用空的objectid引用保存文档-错误:JSON中的ObjectId无效

<div class="post-text" itemprop="text"> <p>I'm working on golang server, connected to mongo.</p> <p>I have a the following reference structure:</p> <pre><code>type A struct { Id bson.ObjectId `bson:"_id" json:"id"` B bson.ObjectId `bson:"b,omitempty" json:"b,omitempty"` } </code></pre> <p>Thing is, B is not mandatory in A, and when ever I try to save A without B i'm getting an error: </p> <pre><code>"Invalid ObjectId in JSON: null" </code></pre> <p>How can I have this reference be no mandatory?</p> </div>

json_decode解析的问题

![如图返回值](https://img-ask.csdn.net/upload/201504/10/1428652653_548893.png) $jsoninfo = json_decode($result); $errcode = $jsoninfo -> errcode; //正常 $errmsg = $jsoninfo -> errmsg; //正常 $card = $jsoninfo -> card; $cardid = $card -> card_id; //null $cardid应该怎么取啊,取出来为空,上面的操作不行,求助各位!

关于python的could not convert string to float的问题。

#!/usr/bin/env python3 #-*- coding: utf-8 -*- import time import subprocess import os from subprocess import call import csv #change offset here offset_peak = 45.0 offset_rsm = 40.0 header_csv = ("time", "amplitude", "rms") try: while True: #pkill because sometimes my microphone was busy subprocess.call("pkill -9 sox | pkill -9 arecord",shell= True) time.sleep( 1 ) #time filedate = time.strftime("%Y%m%d-%H%M%S") filename = "/home/pi/noise/mp3/" + time.strftime("%Y%m%d") + "/" + filedate + ".mp3" filename_csv = "/home/pi/noise/csv/" + time.strftime("%Y%m%d") + ".csv" filedate_csv = time.strftime("%Y-%m-%d %H:%M") terminal_time = time.strftime("%H:%M ") #record subprocess.call("arecord -D hw:1,0 -d 10 -v --fatal-errors --buffer-size=192000 -f dat -t raw --quiet | lame -r --quiet --preset standard - " + filename,shell= True) proc = subprocess.getoutput("sox " + filename + " -n stat 2>&1 | grep 'Maximum amplitude' | cut -d ':' -f 2") proc_rms = subprocess.getoutput("sox " + filename + " -n stat 2>&1 | grep 'RMS.*amplitude' | cut -d ':' -f 2") os.system('clear') proc1 = proc.strip() proc1 = float(proc1) proc_rms = proc_rms.strip() proc_rms = float(proc_rms) #test your microphone in 5 dB steps and create the function e.g. with mycurvefit.com #Fkt 3 30-80 dB proc3 = 83.83064 + (28.34183 - 83.83064)/(1 + (proc1/0.04589368)**1.006258) #Fkt RMS 30-80 dB proc3_rms = 87.69054 + (23.81973 - 87.69054)/(1 + (proc_rms/0.01197014)**0.7397556) #add db filextentions: peak - rms ext_peak = int(round(proc3, 0)) ext_rms = int(round(proc3_rms, 0)) print("Measured values: " + str(proc1) + " / " + str(proc_rms) + " / " + str(proc3) + " / " + str(proc3_rms) + " / " + str(ext_peak) + "\n") #csv file_exists = os.path.isfile(filename_csv) daten_csv = (filedate_csv, proc3, proc3_rms) with open(filename_csv, 'a', newline='') as f: writer = csv.writer(f) if not file_exists: writer.writerow(header_csv) writer.writerow(daten_csv) if proc3 >= offset_peak or proc3_rms >= offset_rsm: print(terminal_time + "Sound detected - save: " + filedate + ".mp3 \n") os.rename(filename, "/home/pi/noise/mp3/" + time.strftime("%Y%m%d") + "/" + filedate + "-" + str(ext_peak) + "-" + str(ext_rms) + ".mp3") time.sleep( 3 ) #os.system('clear') else: print(terminal_time + "No sound detected, delete: " + filedate + ".mp3 \n") os.remove(filename) time.sleep( 3 ) #os.system('clear') except KeyboardInterrupt: subprocess.call("pkill -9 sox | pkill -9 arecord",shell= True) print('End') 详细代码如上,当我运行的时候不知为何python shell显示错误,错误信息如下: Trackback (most recent call last): File:"/home/pi/noise_level_protocol-master/detect.py, line 30 in <module> proc1 = float(proc1) ValueError: could not convert string to float: 希望论坛里的各位大神能够指点迷津, 谢谢。

ValueError: too many values to unpack (expected 2)

网上说是元素找不到对应的 代码如下: ``` import turtle file=open("C:/Users/jyz_1/Desktop/新建文本文档.txt") file=file.read() lines=file.split("重庆") i=0 lsy=[] for line in lines: #index the temprature inn=line.index('\n')#The first \n inc=line.index("C")#The first C if i==0: tu=int(line[line.find('\n',inn+1)+1:inc])#The second \n if "~" in line: tl=int(line[line.index('~')+1:line.rindex('C')]) else: tl=tu i=i+1 else: fn=line.find('\n',inn+1) tu=int(line[line.find('\n',fn+1)+1:inc])#The third \n if "~" in line: tl=int(line[line.index('~')+1:line.rindex('C')]) else: tl=tu t=(tl+tu)/2#daily average temprature lsy.append(t) #find the date lsx=[] dates=file.split("\n") for date in dates: if "-" in date: if date.replace("-","").isnumeric()==True: p1=date.index('-')#the first - p2=date.find('-',p1+1)#the second - month=date[p1+1:p2] day=date[p2+1:] date_on_x=int(month+day) lsx.append(date_on_x) #draw axis def drawx(): turtle.pu() turtle.goto(-50,-50) turtle.pd() turtle.fd(240) def drawy(): turtle.pu() turtle.goto(-50,-50) turtle.seth(90) turtle.pd() turtle.fd(160) #comment the axis def comx(): turtle.pu() turtle.goto(-50,-65) turtle.seth(0) for i in range(1,13): turtle.write(i) turtle.fd(20) def comy(): turtle.pu() turtle.goto(-75,-50) turtle.seth(90) for i in range(-30,51,10): turtle.write(float(i)) turtle.fd(20) #draw the rainbow def rainbow(): #define the color if t<8: turtle.color("purple") elif 8<=t<12: turtle.color("lightblue") elif 12<=t<22: turtle.color("green") elif 22<=t<28: turtle.color("yellow") elif 28<=t<30: turtle.color("orange") elif t>=30: turtle.color("red") #let's draw! for x,t in lsx,lsy: turtle.pu() turtle.goto(x,t) turtle.pd() turtle.circle(10) drawx() drawy() comx() comy() rainbow() ``` 报错: ``` Traceback (most recent call last): File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python37-32\32rx.py", line 92, in <module> rainbow(t) File "C:\Users\jyz_1\AppData\Local\Programs\Python\Python37-32\32rx.py", line 83, in rainbow for x,t in lsx,lsy: ValueError: too many values to unpack (expected 2) ``` 但是我用len发现lsx,lsy长度相同 也就是说,lsx,lsy中的元素一一对应 那这个报错是怎么回事?

python操作word报错ValueError: can only parse strings。

1、问题描述: 学习Python操作word文件,使用render()方法时报错ValueError: can only parse strings。 2、相关代码 ``` # _*_ encoding:utf-8 _*_ from docxtpl import DocxTemplate data_dic = { 't1':'燕子', 't2':'杨柳', 't3':'桃花', 't4':'针尖', 't5':'头涔涔', 't6':'泪潸潸', 't7':'茫茫然', 't8':'伶伶俐俐', } doc = DocxTemplate("/test/test.doc") #加载模板文件 doc.render(data_dic) #填充数据 doc.save("/test/target.doc") ``` 3、模板信息: ``` {{r t1}}去了,有再来的时候;{{r t2}}枯了,有再青的时候;{{r t3}}谢了,有再开的时候。但是,聪明的,你告诉我,我们的日子为什么一去不复返呢?——是有人偷了他们罢:那是谁?又藏在何处呢?是他们自己逃走了罢:现在又到了哪里呢? 我不知道他们给了我多少日子;但我的手确乎是渐渐空虚了。在默默里算着,八千多日子已经从我手中溜去;像{{r t4}}上一滴水滴在大海里,我的日子滴在时间的流里,没有声音,也没有影子。我不禁{{r t5}}而{{r t6}}了。 去的尽管去了,来的尽管来着;去来的中间,又怎样地匆匆呢?早上我起来的时候,小屋里射进两三方斜斜的太阳。太阳他有脚啊,轻轻悄悄地挪移了;我也{{r t7}}跟着旋转。于是——洗手的时候,日子从水盆里过去;吃饭的时候,日子从饭碗里过去;默默时,便从凝然的双眼前过去。我觉察他去的匆匆了,伸出手遮挽时,他又从遮挽着的手边过去,天黑时,我躺在床上,他便{{r t8}}地从我身上跨过,从我脚边飞去了。等我睁开眼和太阳再见,这算又溜走了一日。我掩着面叹息。但是新来的日子的影儿又开始在叹息里闪过了。 ``` 4、报错信息: ![图片说明](https://img-ask.csdn.net/upload/202001/15/1579068250_471502.png) 5、相关依赖包版本 ``` doc 0.1.0 docx 0.2.4 docxtpl 0.6.3 lxml 3.2.1 Jinja2 2.10.3 ``` 6、我尝试更换了lxml的版本发现报错信息一样。我又尝试跟踪错误,在这个文件里: ![图片说明](https://img-ask.csdn.net/upload/202001/15/1579068951_317573.png) 打印了一下text: ![图片说明](https://img-ask.csdn.net/upload/202001/15/1579068974_898727.png) 发现有一步text为None: ![图片说明](https://img-ask.csdn.net/upload/202001/15/1579069045_944104.png) 7、所以想问一下有没有大佬遇到并解决过这个问题,怎么解决这个问题。救救一下小萌新吧,还有就是val._target._blob这个变量里存的是什么数据,为什么会出现None的情况?谢谢大佬的指点! 8、追加: 问题暂时得到了解决,我在get_headers_footers_xml这个函数里添加了不为空的判断if val._target._blob != None:yield relKey, self.xml_to_string(parse_xml(val._target._blob)) 就不再报错并且成功写入到目标文件里,但是我仍然不清楚这是不是依赖包本身的BUG。如果有大佬知道的话请指点我一下。如果也有遇到这个问题的朋友,可以试一试我这个方法暂时解决一下。下面是我修改的图片: ![图片说明](https://img-ask.csdn.net/upload/202001/15/1579074850_454765.png)

python UnicodeDecodeError: 'ascii' codec can't...

错误代码如下: Traceback (most recent call last): File "D:\workspace\GP\ppp.py", line 45, in <module> send_message(url,test_token, msg_data) File "D:\workspace\GP\ppp.py", line 27, in send_message respone=urllib2.urlopen(temp1).read().decode() File "C:\Python27\lib\urllib2.py", line 154, in urlopen return opener.open(url, data, timeout) File "C:\Python27\lib\urllib2.py", line 429, in open response = self._open(req, data) File "C:\Python27\lib\urllib2.py", line 447, in _open '_open', req) File "C:\Python27\lib\urllib2.py", line 407, in _call_chain result = func(*args) File "C:\Python27\lib\urllib2.py", line 1241, in https_open context=self._context) File "C:\Python27\lib\urllib2.py", line 1195, in do_open h.request(req.get_method(), req.get_selector(), req.data, headers) File "C:\Python27\lib\httplib.py", line 1042, in request self._send_request(method, url, body, headers) File "C:\Python27\lib\httplib.py", line 1082, in _send_request self.endheaders(body) File "C:\Python27\lib\httplib.py", line 1038, in endheaders self._send_output(message_body) File "C:\Python27\lib\httplib.py", line 880, in _send_output msg += message_body UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 114: ordinal not in range(128) 原来代码: import json import urllib2 def messages(msg): values = { "touser": 'qy01c75a831f17d000b3d5498cfc', "msgtype": 'text', "agentid": 1000026, "text": {'content': msg}, "safe": 0 } msges= json.dumps(values, ensure_ascii=False, encoding="utf-8") return msges def get_token(url, corpid, corpsecret): token_url = '%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s' % (url, corpid, corpsecret) token = json.loads(urllib2.urlopen(token_url).read().decode())['access_token'] print token return token def send_message(url,token, data): send_url = '%s/cgi-bin/message/send?access_token=%s' % (url,token) print send_url temp1=urllib2.Request(url=send_url, data=data) print temp1 respone=urllib2.urlopen(temp1).read().decode() x = json.loads(respone)['errcode'] # print(x) if x == 0: print ('Succesfully') else: print ('Failed') msg='中文' #此处有中文是出错,英文时没错,为什么呢??? print type(msg) # print msg corpid = '**********************' corpsecret = '******************************************' url = 'https://qyapi.weixin.qq.com' msg_data= messages(msg) print msg_data test_token=get_token(url, corpid, corpsecret) send_message(url,test_token, msg_data)

错误提示ValueError: unsupported format character

应该是这一段 '''将方法体中的host字段进行替换''' def get_raw_body(self, req, ip): ip = self.get_host_from_url(ip) host_reg = re.compile(r'Host:\s([a-z\.A-Z0-9]+)') host = host_reg.findall(req) if not host or host[0] == '': print ('[-]ERROR MESSAGE!Wrong format for request body') sys.exit() req, num = re.subn(host_reg, "Host: %s", req) return req % ip 错误提示: return req % (ip) ValueError: unsupported format character '{' (0x7b) at index 31 源程序是2.7,我的是3.6,不想卸载去下2.7,为了这一个程序不值得...

Keras报错 ‘ValueError: 'pool5' is not in list’

很长的一个project,在keras下实现VGG16。 这是报错的整个代码段: ``` for roi, roi_context in zip(rois, rois_context): ins = [im_in, dmap_in, np.array([roi]), np.array([roi_context])] print("Testing ROI {c}") subtimer.tic() blobs_out = model.predict(ins) subtimer.toc() print("Storing Results") print(layer_names) post_roi_layers = set(layer_names[layer_names.index("pool5"):]) for name, val in zip(layer_names, blobs_out): if name not in outs: outs[name] = val else: if name in post_roi_layers: outs[name] = np.concatenate([outs[name], val]) c += 1 ``` 报错信息: ``` Loading Test Data data is loaded from roidb_test_19_smol.pkl Number of Images to test: 10 Testing ROI {c} Storing Results ['cls_score', 'bbox_pred_3d'] Traceback (most recent call last): File "/Users/xijiejiao/Amodal3Det_TF/tfmodel/main.py", line 6, in <module> results = test_main.test_tf_implementation(cache_file="roidb_test_19_smol.pkl", weights_path="rgbd_det_iter_40000.h5") File "/Users/xijiejiao/Amodal3Det_TF/tfmodel/test_main.py", line 36, in test_tf_implementation results = test.test_net(tf_model, roidb) File "/Users/xijiejiao/Amodal3Det_TF/tfmodel/test.py", line 324, in test_net im_detect_3d(net, im, dmap, test['boxes'], test['boxes_3d'], test['rois_context']) File "/Users/xijiejiao/Amodal3Det_TF/tfmodel/test.py", line 200, in im_detect_3d post_roi_layers = set(layer_names[layer_names.index("pool5"):]) ValueError: 'pool5' is not in list ```

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Linux面试题(2020最新版)

文章目录Linux 概述什么是LinuxUnix和Linux有什么区别?什么是 Linux 内核?Linux的基本组件是什么?Linux 的体系结构BASH和DOS之间的基本区别是什么?Linux 开机启动过程?Linux系统缺省的运行级别?Linux 使用的进程间通信方式?Linux 有哪些系统日志文件?Linux系统安装多个桌面环境有帮助吗?什么是交换空间?什么是root帐户什么是LILO?什...

Linux命令学习神器!命令看不懂直接给你解释!

大家都知道,Linux 系统有非常多的命令,而且每个命令又有非常多的用法,想要全部记住所有命令的所有用法,恐怕是一件不可能完成的任务。 一般情况下,我们学习一个命令时,要么直接百度去搜索它的用法,要么就直接用 man 命令去查看守冗长的帮助手册。这两个都可以实现我们的目标,但有没有更简便的方式呢? 答案是必须有的!今天给大家推荐一款有趣而实用学习神器 — kmdr,让你解锁 Linux 学习新姿势...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

史上最全的 python 基础知识汇总篇,没有比这再全面的了,建议收藏

网友们有福了,小编终于把基础篇的内容全部涉略了一遍,这是一篇关于基础知识的汇总的文章,请朋友们收下,不用客气,不过文章篇幅肯能会有点长,耐心阅读吧爬虫(七十)多进程multiproces...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

85后蒋凡:28岁实现财务自由、34岁成为阿里万亿电商帝国双掌门,他的人生底层逻辑是什么?...

蒋凡是何许人也? 2017年12月27日,在入职4年时间里,蒋凡开挂般坐上了淘宝总裁位置。 为此,时任阿里CEO张勇在任命书中力赞: 蒋凡加入阿里,始终保持创业者的冲劲,有敏锐的...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

新一代神器STM32CubeMonitor介绍、下载、安装和使用教程

关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

大学一路走来,学习互联网全靠这几个网站,最终拿下了一把offer

大佬原来都是这样炼成的

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

什么时候跳槽,为什么离职,你想好了么?

都是出来打工的,多为自己着想

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你期望月薪4万,出门右拐,不送,这几个点,你也就是个初级的水平

先来看几个问题通过注解的方式注入依赖对象,介绍一下你知道的几种方式@Autowired和@Resource有何区别说一下@Autowired查找候选者的...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

立即提问
相关内容推荐