这是我使用的文本文件的内容:
[{"name": "Bitcoin", "symbol": "BTC", "rank": 1, "slug": "bitcoin", "tokens": ["Bitcoin", "bitcoin", "BTC"], "id": 1},
{"name": "Ethereum", "symbol": "ETH", "rank": 2, "slug": "ethereum", "tokens": ["Ethereum", "ethereum", "ETH"], "id": 1027}, ... ]
如何检索每个硬币的每个"name“元素并将其保存到一个临时变量中?
发布于 2018-05-31 05:36:31
这看起来像是一个有效的JSON
,所以只需使用内置的json
模块来解析它,例如:
import json
with open("path/to/your_file.txt", "r") as f: # open the file for reading
data = json.load(f) # parse it as JSON
# now you can access the data hierarchically, i.e.
print("The first coin is {} and its symbol is {}".format(data[0]["name"], data[0]["symbol"]))
# The first coin is Bitcoin and its symbol is BTC
# or if you want just a list of all names
coin_names = [d["name"] for d in data] # ['Bitcoin', 'Ethereum', ...]
发布于 2018-05-31 06:05:26
如果您喜欢使用第三方库,pandas
会直接接受字典列表:
import pandas as pd
from io import StringIO
import json
mystr = StringIO("""[{"name": "Bitcoin", "symbol": "BTC", "rank": 1,
"slug": "bitcoin", "tokens": ["Bitcoin", "bitcoin", "BTC"], "id": 1},
{"name": "Ethereum", "symbol": "ETH", "rank": 2, "slug": "ethereum",
"tokens": ["Ethereum", "ethereum", "ETH"], "id": 1027}]""")
# replace mystr with 'file.json'
df = pd.read_json(mystr)
# extract names to list
res = df['name'].tolist()
print(res)
['Bitcoin', 'Ethereum']
https://stackoverflow.com/questions/50613346
复制相似问题