簡體   English   中英

如何從字符串中拉出某個段

[英]How do I pull out a certain segment from a string

我正在使用給我的 API 和 output 格式為

 ['{"quote":{"symbol":"AAPL"', '"companyName":"Apple Inc."', '"primaryExchange":"Nasdaq Global Select"', '"sector":"Technology"', '"calculationPrice":"close"', '"open":367.88', '"openTime":1593696600532', '"close":364.11', '"closeTime":1593720000277', '"high":370.47', '"low":363.64', '"latestPrice":364.11'}]

...(它繼續像這樣,有更多的類別。)

我試圖只提取最新價格。 最好的方法是什么?

這就是我所擁有的,但我得到了一堆錯誤。

string = (data.decode("utf-8"))
    data_v = string.split(',')

    for word in data_v[latestPrice]:
        if word == ["latestPrice"]:
            print(word)


    print(data_v)

從 output 判斷,這是 JSON。 To parse this easily use the JSON module (see https://docs.python.org/3/library/json.html ).

如果我是正確的,您從 Yahoo Finance 獲得了此 output,如果確實如此,請不要手動獲取和解析它,而是使用 yfinance 模塊(請參閱https://pypi.org/project/yfinance/

您必須使用JSON模塊來解析此JSON字符串。 你可以把它轉換成字典。 為了便於理解,我縮進了 JSON 代碼。 您可以使用以下方法,

import json

text_to_parse = """
  {"quote":
     {
         "symbol":"AAPL",
          "companyName":"Apple Inc.",
          "primaryExchange":"Nasdaq Global Select",
          "sector":"Technology",
          "calculationPrice":"close",
          "open":367.88,
          "openTime":1593696600532,
          "close":364.11,
          "closeTime":1593720000277,
          "high":370.47,
          "low":363.64,
          "latestPrice":364.11
     }
 }
"""

parsed_dict = json.loads(text_to_parse)
print(parsed_dict["quote"]["latestPrice"])

程序運行時輸出364.11

暫無
暫無

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

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