【问题标题】:Python 3.5.1 : NameError: name 'json' is not definedPython 3.5.1:NameError:未定义名称“json”
【发布时间】:2017-04-21 11:34:30
【问题描述】:
#!/usr/bin/env python
# encoding: utf-8

import tweepy #https://github.com/tweepy/tweepy
import json as simplejson


    #write tweet objects to JSON
    file = open('tweet.json', 'wb') 
    print ("Writing tweet objects to JSON please wait...")
    for status in alltweets:
        json.dump(status._json,file,sort_keys = True,indent = 4)

    #close the file
    print ("Done")
    file.close()

if __name__ == '__main__':
    #pass in the username of the account you want to download
    get_all_tweets("@AlertZaAfrica")

python 编译器说第 54 行是错误的。我已经将 import json 定义为 simplejson。上面我定义了 import json 的区域如上所示。

【问题讨论】:

  • 请显示您定义它的位置。
  • 那就是为什么……你的意思是import simplejson as json?如果您仍然使用 Python 3.5,为什么不直接使用 import json
  • 好的,我来分享完整代码
  • import simplejson as json

标签: python python-3.5


【解决方案1】:

您应该首先将 simplejson 安装到您的系统以便能够导入它:

$ sudo pip3 install simplejson

然后在您的代码中您现在可以导入它:

import simplejson as json

从现在开始,您将能够使用 json 访问 simplejson 包。

请注意,如果您仍在使用 python 2 - 尽管这不是 OP 的原始问题 - 您应该这样做

$ sudo pip install simplejson

改为。

【讨论】:

  • 我安装了它,但我的 python 仍然没有找到它。
  • @ScottyBlades 我猜,你的系统 python 不是版本 3。由于这里的问题是关于 python3,你可能应该做一个简单的 pip install simplejson 代替,所以你的系统 python,可能是版本 2 , 安装 thje simplejson 包。 HTH
猜你喜欢
  • 1970-01-01
  • 2013-01-26
  • 1970-01-01
  • 2020-09-04
  • 2021-10-18
  • 2016-08-09
  • 2016-01-08
  • 2021-07-22
相关资源
最近更新 更多