首页 > 解决方案 > 从 csv 文件解析 d3 .v5 中的 BC 日期

问题描述

我将维基百科中显示世界历史上所有战争的表格转换为 csv 文件,以根据这些数据构建散点图。

CSV 格式:

War,Deathrange,Geometricmean(Note 1),Date,Combatants,Location,Notes
Conquests of Cyrus the Great,"100,000+","100,000",549 BC–530 BC,Persian Empire vs. various states,Middle East,"Number given is the sum of all deaths in battle recorded by writers during this time period, does not take into account civilian deaths, the actual number may be much greater."
Greco–Persian Wars,

我想在 X 轴上获取“日期”的第一个日期——例如“549”。圆点的半径应该与战争的持续时间有关。

问题 我不知道如何在 d.3 中解析“BC”日期

到目前为止,我做到了: 我的方法是使用正则表达式查找字符串中的数字。

let dataset = await d3.csv("../wars.csv");
let dateNumber = dataset[0].Date.match(/\d+/g);

要检查日期是否包含“BC”并将其转换为“减号”,我做了:

 if (dataset[0].Date.includes("BC")) {
        const warStart = "-" + dateNumber[0];
        const warEnd = "-" + dateNumber[1];
        console.log(warStart + " and ends " + warEnd)

    }

我不知道如何在所有日期上应用这种方法——而不仅仅是 [0]

我试过了

 const dates = d => d.Date.match(/\d+/g);
    console.log(dates);

控制台正在记录:

function dates()

但没有日期,即使索引像“日期[1]”

那么如何以某种格式解析 CSV 中包含“BC”的日期,从而使 d3 时间特征能够在 x 轴上显示它们?

因为我对 JS 和 d3 非常陌生,所以我感谢有用的资源。

最好的,谢谢。

标签: javascriptdated3.js

解决方案


推荐阅读