相关疑难解决方法(0)

为什么我不能在打开的文件上调用read()两次?

对于我正在进行的练习,我正在尝试使用该read()方法两次读取给定文件的内容.奇怪的是,当我第二次调用它时,它似乎没有将文件内容作为字符串返回?

这是代码

f = f.open()

# get the year
match = re.search(r'Popularity in (\d+)', f.read())

if match:
  print match.group(1)

# get all the names
matches = re.findall(r'<td>(\d+)</td><td>(\w+)</td><td>(\w+)</td>', f.read())

if matches:
  # matches is always None
Run Code Online (Sandbox Code Playgroud)

当然我知道这不是最有效或最好的方式,这不是重点.关键是,为什么我不能read()两次打电话?我是否必须重置文件句柄?或者关闭/重新打开文件以执行此操作?

python io

86
推荐指数
4
解决办法
6万
查看次数

Python-请求-JSONDecodeError

我有这个代码:

import requests

r = requests.get('https://www.instagram.com/p/CJDxE7Yp5Oj/?__a=1')
data = r.json()['graphql']['shortcode_media']
Run Code Online (Sandbox Code Playgroud)

为什么我会收到这样的错误?

C:\ProgramData\Anaconda3\envs\test\python.exe C:/Users/Solba/PycharmProjects/test/main.py  
Traceback (most recent call last):  
  File "C:/Users/Solba/PycharmProjects/test/main.py", line 4, in <module>  
    data = r.json()  
  File "C:\ProgramData\Anaconda3\envs\test\lib\site-packages\requests\models.py", line 900, in json  
    return complexjson.loads(self.text, **kwargs)  
  File "C:\ProgramData\Anaconda3\envs\test\lib\json\__init__.py", line 357, in loads  
    return _default_decoder.decode(s)  
  File "C:\ProgramData\Anaconda3\envs\test\lib\json\decoder.py", line 337, in decode  
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())  
  File "C:\ProgramData\Anaconda3\envs\test\lib\json\decoder.py", line 355, in raw_decode  
    raise JSONDecodeError("Expecting value", s, err.value) from None  
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)  
  
Process finished with …
Run Code Online (Sandbox Code Playgroud)

python json python-requests

8
推荐指数
1
解决办法
5万
查看次数

json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)python

我收到以下错误消息:

...文件“c:\users\dockerhost\appdata\local\programs\python\python37\Lib\json\decoder.py”,第 355 行,raw_decode 引发 JSONDecodeError("Expecting value", s, err.value)从无 json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我正在尝试使用请求来获取响应标头。我在尝试解决 jsondecodeerror 方面做了很多研究。但是,我没有找到解决方案。

import requests
request.get('https://www.google.com/').json()

Error message.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Host\.virtualenvs\projects08-8iyGSYl4\lib\site-packages\requests\models.py", line 897, in json
    return complexjson.loads(self.text, **kwargs)
  File "c:\users\host\appdata\local\programs\python\python37\Lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "c:\users\host\appdata\local\programs\python\python37\Lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "c:\users\host\appdata\local\programs\python\python37\Lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: …
Run Code Online (Sandbox Code Playgroud)

python python-requests

5
推荐指数
1
解决办法
2万
查看次数

JSONDecodeError:加载 tf.Keras 模型时需要值

当我尝试加载经过训练的tf.keras模型时,出现错误:JSONDecodeError: Expecting value。该问题不可重现,即,当我尝试加载在集群上训练并下载到计算机上的模型时,出现错误。当我尝试编译、保存和加载同一模型时,错误并未出现。

有什么想法可能是什么问题吗?

以下代码有效(与加载经过训练的模型相反):

import tensorflow as tf
from tensorflow import keras as ks
import numpy as np
import os
def UNet(n_classes, input_shape = (256, 256, 3), dropout = 0.05,
         ops = {"activation" : "relu",
                "padding" : "same",
                "kernel_initializer" : "he_normal"
        }):
    # input layer
    inputz = ks.layers.Input(shape = input_shape)
    
    # encoder part
    ## 1st convolution
    c1 = ks.layers.Conv2D(64, (3, 3), **ops)(inputz)
    c1 = ks.layers.Conv2D(64, (3, 3), **ops)(c1)
    ## 1st max pooling
    p1 …
Run Code Online (Sandbox Code Playgroud)

json python-3.x keras tensorflow

5
推荐指数
1
解决办法
2976
查看次数

为什么我在迭代 28 后收到错误:“JSONDecodeError:期望值:第 1 行第 1 列(字符 0)”?

我正在尝试从政府的 API 中提取数据。该 API 分为多个页面,每页有 10 个观察结果。我编写了一个算法,可以从每个观察中获取重要信息并将其添加到 pandas 数据框中。一切都很顺利,直到我到达迭代 29,此时我收到了标题中提到的错误。

\n

这是我写的代码:

\n
#Database Creation Using API\n#Import Libraries\nimport requests\nimport pandas as pd\n\n#Define a list of relevant variables to automatize information acquisition\nrelevant_vars = ["year","ocid","date","region","title","description","suppliers","buyer","amount"\\\n                 ,"budget"]#Define a list of relevant variables to automatize information acquisition\n\n#Creation of empty Pandas Dataframe to save all the pertinent information from the database.\ndata_collected = pd.DataFrame(columns = relevant_vars)\n\n#Access to API's data\n#API number 1: "B\xc3\xbasqueda de procesos de contrataci\xc3\xb3n por medio de palabra"\n\n#Need an initial response to start while …
Run Code Online (Sandbox Code Playgroud)

python json python-3.x

5
推荐指数
1
解决办法
4万
查看次数

FastAPI GET 端点返回“405 method not allowed”响应

FastAPI 中的端点GET返回正确的结果,但405 method not allowedcurl -I使用时返回。所有GET端点都会发生这种情况。因此,应用程序正在运行,但负载均衡器对应用程序的运行状况检查失败。

有什么建议可能是错误的吗?

代码

@app.get('/health')
async def health():
    """
    Returns health status
    """
    return JSONResponse({'status': 'ok'})
Run Code Online (Sandbox Code Playgroud)

结果

curl http://172.xx.xx.xx:8080
Run Code Online (Sandbox Code Playgroud)

返回标头

curl -I http://172.xx.xx.xx:8080
Run Code Online (Sandbox Code Playgroud)

python rest http-status-code-405 fastapi

5
推荐指数
1
解决办法
7068
查看次数

json响应出了什么问题

json响应正常工作:

obj = urllib.urlopen("http://www.omdbapi.com/?t=Fight Club")
response_str = obj.read()
response_json = simplejson.loads(response_str)
Run Code Online (Sandbox Code Playgroud)

上面的代码发出json请求,如下所示:

{
    "Title":"Fight Club",
    "Year":"1999",
    "Rated":"R",
    "Released":"15 Oct 1999",
     ......
    "Response":"True"
}
Run Code Online (Sandbox Code Playgroud)

我现在可以睡觉了...但是

json响应无法正常工作:

obj = urllib.urlopen("https://api.stackexchange.com/2.1/answers?order=desc&sort=activity&site=stackoverflow")
response_str = obj.read()
response_json = simplejson.loads(response_str)
Run Code Online (Sandbox Code Playgroud)

上面的代码发出json请求,如下所示:

{

    "items": [
        {
            "question_id": 18384375,
            "answer_id": 18388044,
            "creation_date": 1377195687,
            "last_activity_date": 1377195687,
            "score": 0,
            "is_accepted": false,
            "owner": {
                "user_id": 1745001,
                "display_name": "Ed Morton",
                "reputation": 10453,
                "user_type": "registered",
                "profile_image": "https://www.gravatar.com/avatar/99a3ebae89496eb16afe453aae97f5be?s=128&d=identicon&r=PG",
                "link": "/sf/users/122150101/"
            }
        },
        {
            "question_id": 18387447,
            "answer_id": 18388040,
            "creation_date": 1377195667,
            "last_activity_date": 1377195667,
            "score": 0,
            "is_accepted": …
Run Code Online (Sandbox Code Playgroud)

python json

3
推荐指数
1
解决办法
2783
查看次数

当我尝试设置 gcp 服务帐户时,Gitlab ci/cd 作业显示错误(无法读取 json 文件)

$ echo $SERVICE_ACCOUNT_DEV > ${HOME}/gcloud-service-key.json
$ gcloud auth activate-service-account --key-file ${HOME}/gcloud-service-key.json
ERROR: (gcloud.auth.activate-service-account) Could not read json file /root/gcloud-service-key.json: Expecting value: line 2 column 1 (char 1).
Run Code Online (Sandbox Code Playgroud)

我检查了存储在 gitlab ci/cd 变量中的 SERVICE_ACCOUNT_DEV json 文件,但没有问题。

google-cloud-platform gitlab-ci

3
推荐指数
1
解决办法
3380
查看次数