簡體   English   中英

在 python 上打印來自.json 的特定單詞

[英]Print specific words from .json on python

I am using twitter and downloaded a sample code from:" https://stream.twitter.com/1.1/statuses/sample.json "

我使用了漂亮的打印,但它不像我想要的那樣打印。

我只需要用戶“name”或“screen_name”、“user_mention”和“retweeted”。 我需要它來繪制一棵帶有節點(名稱)和邊緣(轉發或提及帶有情感值(+/-)的樹。

第一:我不知道如何從 json 中刪除所有內容,只打印 3 件事。

代碼:


        with open (fname) as json_file:

        for line in json_file.readlines():

            type(line)

            f_contents = json_file.read()

            keywords = ["id","screen_name","retweeted", "user_mention" ]

            keywords =set(keywords)

            print(keywords)

            pprint.pprint(line, indent = 4 , width=5)

如果你想通過鍵過濾一些字典,有一些方法。 您可以查看此線程中討論的解決方案: https://stackoverflow.com/a/3420156/3921457

在您的情況下,一種解決方案可能類似於:

import json 

keywords = {'id','screen_name','retweeted', 'user_mention'}

with open(fname) as file:
    for raw_line in file.readlines():
        full_line = json.loads(line)
        line = {key: full_line[key] for key in keywords}

        pprint.pprint(line, indent = 4 , width=5)
  1. 使用 json 庫將文件實際加載為結構化數據。 嘗試一次讀取一行文件不會很好,因為它忽略了 JSON 的結構; 並且這里的 .read() 調用無論如何都會破壞策略(它將文件的整個 rest 讀取到第一行之外的f_contents中,然后循環不再運行)。

所以:

import json

with open(fname) as json_file:
    data = json.load(json_file)
  1. 使用 Python 操作拉出你需要的部分數據。 您將擁有一個普通的字典或列表,其中包含更多的字典或列表等,嵌套深度與 JSON 一樣。

  2. 現在您可以pprint相關的片段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM