该字符串在Python中不可调用

2024-04-27 22:34:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将dict导出到csv。我正在从api中提取数据,需要将其打印到CSV

我正在使用:

import datetime
import csv
import pendulum
import requests
from tabulate import tabulate
import pandas as pd
import numpy as np

我正在调用的API如下所示:

api_url = "https://secure-webtv-static.canal-plus.com/metadata/cpfra/all/v2.2/globalchannels.json"
response = requests.get(api_url).json()

我想从这里获取数据:

tv_programme = {
    channel["name"]: [
        [
            e['title'],
            e['subTitle'],
            pendulum.parse(e['timecodes'][0]['start']
                           ).time().strftime("%H:%M"),
            datetime.timedelta(
                milliseconds=e['timecodes'][0]['duration'],
            ).__str__().rsplit(".")[0],
        ] for e in channel["events"]
    ] for channel in response["channels"]
}

我正在尝试使用Pandas将数据发送到CSV文件

df = pd.DataFrame(tabulate(
    tv_programme["CANAL+ SPORT"],
    headers="firstrow"("Title", "Subtitle", "Time", "Duration"),
    tablefmt="csv",
))
print(tabulate(
    tv_programme["CANAL+ SPORT"],
    headers=["Title", "Subtitle", "Time", "Duration"],
    tablefmt="csv",
))
df = pd.DataFrame(sorted(list(tv_programme.headers('sports.csv'))))

print收集下面的数据,我需要它来填充CSV文件

Title                                Subtitle     Time    Duration
-----------------------------------  -----------  ------  ----------
Sport Reporter                       Doc Sport    10:42   0:26:23
Chelsea / West Ham                   14e journée  11:11   0:48:38
Cesta punta - Pro Tour 2020          Autre Sport  12:51   1:28:53
Rugby - Golden Lions / Natal Sharks  4e journée   14:20   0:45:56
Rugby - Colomiers / Perpignan        8e journée   15:55   0:50:00
Rugby - Oyonnax / Biarritz           6e journée   17:55   0:50:00
Rugby - Castres / Brive              4e journée   19:55   1:15:00

现在,这就是我被卡住并收到错误的地方:TypeError: 'str' object is not callable


Tags: csv数据importapititlechanneltvheaders
1条回答
网友
1楼 · 发布于 2024-04-27 22:34:53

您需要传递实际的数据结构,而不是由tabulate构建的字符串

例如:

df = pd.DataFrame(tv_programme["CANAL+"], columns=["Title", "Subtitle", "Time", "Duration"])
df.to_csv("canal_plus.csv", index=False)

这将为您提供:

enter image description here

相关问题 更多 >