计算 CSV 文件中某个单词出现的次数

Count how many occurrences of a word are there in CSV file

我有一个包含这样数据的 csv 文件

PassengerId,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
111,1,"Ken, Mr. James",male,34.5,0,0,330911,7.8292,,A
112,2,"Will, Mrs. James",female,47,1,0,363272,7,,B
and so on 

我想统计 csv 文件中的这些名字中有多少包括 Mr 和 Mrs 以及其他人

并使用列'sex'我想打印男性和女性乘客的人数。

我已经试过了,但它只是打印每一行,Mrs 为 0,Mr 为 1,而不是给我 Names with Mr.

的计数

我不知道如何遍历 csv 数据,有人可以为此添加代码部分吗?谢谢

<script src='https://d3js.org/d3.v7.min.js'></script>

<script>
            let mycsv = ' some file name';

d3.csv(mycsv, function(data) {
let count = 0;
var theWord  = "Mr";

    if (data.Name.includes(theWord))
    {
        count++;
    }
        
console.log(count);
});

</script>
  1. 您需要 then 来自版本 5+

    let mycsv = 'example.csv';
    d3.csv(mycsv)
    .then(function(data) {
      /* process data */
    })
    
  2. 你需要循环。

可以用 reduce:

https://plungjan.name/SO/d3csv/

const process = data =>  {
  const counts = data.reduce((acc, { Name, Sex, Age }) => {
    acc.mr     += Name.toLowerCase().includes("mr.");
    acc.mrs    += Name.toLowerCase().includes("mrs.");
    acc.male   += Sex.toLowerCase() === "male";
    acc.female += Sex.toLowerCase() === "female";
    acc.age    += +Age
    return acc;
  }, { mr: 0, mrs: 0, male: 0, female: 0, age: 0 });
  
  console.log("Total age",counts.age)
  
  Object.entries(counts).forEach(([key,val]) => document.getElementById(key).textContent = val)
}

// uncomment when you want to read a file

// let mycsv = 'example.csv';
// d3.csv(mycsv)
//.then(function(data) {
  process(data)
//})
<script src='https://d3js.org/d3.v7.min.js'></script>
<script>
  const data = d3.csvParse(`PassengerId,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
111,1,"Ken, Mr. James",male,34.5,0,0,330911,7.8292,,A
112,2,"Will, Mrs. James",female,47,1,0,363272,7,,B`);
</script>

Mr: <span id="mr"></span><br/>
Mrs: <span id="mrs"></span><br/>
Male: <span id="male"></span><br/>
Female: <span id="female"></span><br/>
Sum of Ages <span id="age"></span><br/>

如果您只想统计 30 岁以上的人数:

const process = data =>  {
  const ages = data.map(({Age}) => +Age) // make sure it is a number
  .filter(num => num > 30).length

  console.log("Total of ppl with age above 30:",ages)
}

// uncomment when you want to read a file

// let mycsv = 'example.csv';
// d3.csv(mycsv)
//.then(function(data) {
  process(data)
//})
<script src='https://d3js.org/d3.v7.min.js'></script>
<script>
  const data = d3.csvParse(`PassengerId,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
111,1,"Ken, Mr. James",male,34.5,0,0,330911,7.8292,,A
112,2,"Will, Mrs. James",female,47,1,0,363272,7,,B`);
</script>