【问题标题】:error in python: No JSON object could be decodedpython中的错误:无法解码JSON对象
【发布时间】:2019-01-21 19:50:39
【问题描述】:

我正在尝试在推文中找到最常用的词。我对 txt 文件进行了标记并将令牌传递到 json 文件中,但是当我执行 json.loads 时,它给了我一个错误:没有 JSON 对象可以被解码。

  s_tweets.head()
  print(s_tweets.iloc[:,2])
  tweets = s_tweets.iloc[:,2]
  #step 2: remove the special characters and punctuation
  tlist = []
  for t in tweets:
      t_new=re.sub('[^A-Za-z0-9]+', ' ', t)
      tlist.append(t_new)
      #print(t_new)
      #print(t_list)


 test=word_tokenize(tlist[1])
 print(test)


  fname = 'tokensALL.json'
  ff = open(fname, 'a')
  for i in range(0,1751):
          ff.write(str(word_tokenize(tlist[i])) + "\n")

   ff.close()



  ###### find most frequent words


  fname2 = 'tokensALL.json'
  with open(fname2, 'r') as f:
      count_all = Counter()
      for line in f:
          tweet = json.loads(line)
          # Create a list with all the terms
          terms_stop = [term for term in preprocess(tweet['text']) if 
  term not in stop]
          # Update the counter
          # terms_single = set(terms_all)
          # Count hashtags only
          terms_hash = [term for term in preprocess(tweet['text'])
                        if term.startswith('#')]
          # Count terms only (no hashtags, no mentions)
          terms_only = [term for term in preprocess(tweet['text'])
                        if term not in stop and
                        not term.startswith(('#', '@'))]
          # mind the ((double brackets))
          # startswith() takes a tuple (not a list) if
          # we pass a list of inputs
          terms_single = set(terms_stop)
          terms_bigram = bigrams(terms_stop)
         count_all.update(terms_stop)

      # Print the first 5 most frequent words
      print(count_all.most_common(5))

这是我的代码和 json 文件内容示例( ['哭','为','帮助','喜欢','眼泪','in','rain'] ['rain', 'rain', 'go', 'away']...等)

有人可以帮忙解决这个问题吗?谢谢!

【问题讨论】:

  • 您真的需要多于两行 (line="['cries', 'for', 'help', 'like', 'tears', 'in', 'rain']"; json.loads(line)) 来重现该错误吗?见minimal reproducible example 定义;为了与相同的最小方面保持一致,复制器应该是生成相同错误的最简单的代码
  • 顺便说一句,您的输入真的是 JSON,还是 JSONL?尝试为文件中的每一行调用 json.loads(line) 仅适用于 JSONL 文件(也就是说,每一行都是单独的有效 JSON 文档的文件),而不是 JSON 文件.
  • 鉴于您正在写信给tokensALL.json,听起来您并不知道 JSON 是什么或它的样子。您可能应该先阅读 JSON。
  • 它无法解码您的 JSON,因为您显示的 JSON 无效。
  • 您能解释一下为什么它无效吗?谢谢

标签: python json


【解决方案1】:

您必须检查您的 json 格式是否为有效的 json。这是一篇讨论所有可能性以及如何检查它是否是有效 json 的帖子。 previous post

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2014-06-21
    • 1970-01-01
    • 2015-03-29
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    相关资源
    最近更新 更多