【问题标题】:python runs slow while executing below piece of codepython在执行下面的代码时运行缓慢
【发布时间】:2018-09-16 22:49:37
【问题描述】:
tag_api=”htpps://url....”  
json_data=requests.get(tag_api)  
length=len(json_data[‘tags’])  
line=0  
while length>=2:  
    if line<=lenght-1:  
        with open(‘file.txt’,’a’) as fp:  
            fp.write(json_data[‘tags’][line][‘name’])  
            line=line+1  

当我运行这段代码时,它在 while 循环中变慢了。您认为可能是什么问题?

{ { { "id": "", "category": "", "type": "", "tags": { "id": "", "name": "" } { "id": "", "name": "" } }, { "id": "", "category": "", "type": "", "tags": { "id": "", "name": "" } }, { "id": "", "category": "", "type": "", "tags": { "id": "", "name": "" } }, { "id": "", "category": "", "type": "", "tags": { "id": "", "name": "" } { "id": "", "name": "" } }, } }

我正在尝试获取具有两个以上索引的标签并写入文件

【问题讨论】:

  • 有几个拼写错误。是你输入的代码,还是真的是这样的?
  • @chrisz 感谢您的纠正。我必须输入代码并且有拼写错误。您发现代码有什么问题吗?
  • @Raghu 只是复制粘贴,还是有不少错误。我刚刚格式化了。
  • { { { "id": "", "category": "", "type": "", "tags": { "id": "", "name": "" } { "id": "", "name": "" } }, { "id": "", "category": "", "type": "", "tags": { "id": " ", "name": "" } }, { "id": "", "category": "", "type": "", "tags": { "id": "", "name": " " } }, ] } } 我正在尝试打印具有两个以上索引的标签,并且我的 json 文件看起来像上面
  • 只要“python”作为标签就足够了,如果代码不是特定于一个或另一个。

标签: linux python-2.7


【解决方案1】:

打开一个文件(然后关闭它)是相当慢的操作。由于每次都是同一个文件,所以尽量把开口往外移。

【讨论】:

  • 谢谢@Arndt Jonasson 你有没有更好的代码来获取具有两个以上索引的标签..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 2016-03-28
  • 2015-03-11
  • 1970-01-01
  • 2021-02-08
相关资源
最近更新 更多