首页 > 解决方案 > 尝试从 coinmarketcap API 解析信息

问题描述

目前正在编写一些代码来组织我从 API 收到的数据。

它带有键和值,但我还没有找到一种方法来制作一个整洁的 CSV,其中包含键的列和值的行。

当数据通过 API 进入时,它存储在一个 txt 文件中。

我拿那个 txt 文件并通过用 \n 替换行尾的一个字符来对其进行排序。

# Read in the file
with open('latest_out.txt', 'r') as file :
    filedata = file.read()
    # Replace the target string
    filedata = filedata.replace('}}},', '\n')
    # Write the file out again
    with open('latest_out_sorted.txt', 'w') as file:
    file.write(filedata)

这给了我每个 CryptoCurrency 的部分。

但我需要将其写入包含列和值的 CSV。

文本示例:

{'id': 1, 'name': 'Bitcoin', 'symbol': 'BTC', 'slug': 'bitcoin', 'num_market_pairs': 9716, 'date_added': '2013-04-28T00:00:00.000Z', 'tags': ['mineable', 'pow', 'sha-256', 'store-of-value', 'state-channels', 'coinbase-ventures-portfolio', 'three-arrows-capital-portfolio', 'polychain-capital-portfolio'], 'max_supply': 21000000, 'circulating_supply': 18636068, 'total_supply': 18636068, 'platform': None, 'cmc_rank': 1, 'last_updated': '2021-02-23T02:28:02.000Z', 'quote': {'CAD': {'price': 65576.2472947517, 'volume_24h': 112161256452.41504, 'percent_change_1h': -2.63752472, 'percent_change_24h': -8.8113568, 'percent_change_7d': 6.37461057, 'percent_change_30d': 62.70380758, 'market_cap': 1222083403769.8086, 'last_updated': '2021-02-23T02:28:05.000Z'
 {'id': 1027, 'name': 'Ethereum', 'symbol': 'ETH', 'slug': 'ethereum', 'num_market_pairs': 5997, 'date_added': '2015-08-07T00:00:00.000Z', 'tags': ['mineable', 'pow', 'smart-contracts', 'coinbase-ventures-portfolio', 'three-arrows-capital-portfolio', 'polychain-capital-portfolio'], 'max_supply': None, 'circulating_supply': 114783223.6865, 'total_supply': 114783223.6865, 'platform': None, 'cmc_rank': 2, 'last_updated': '2021-02-23T02:28:02.000Z', 'quote': {'CAD': {'price': 2147.126992405774, 'volume_24h': 52728131634.694145, 'percent_change_1h': -3.49137429, 'percent_change_24h': -11.16189412, 'percent_change_7d': -6.56833787, 'percent_change_30d': 37.20883417, 'market_cap': 246454157852.63397, 'last_updated': '2021-02-23T02:28:05.000Z'

希望这有助于理解我的目标是什么。希望能够将数据从 CSV 直接读取到网页。

谢谢,

标签: pythonapicsvreadlines

解决方案


推荐阅读