gpt4 book ai didi

rust - 我如何通过询问 "can it be turned into a number"来移植识别值属于哪个 CSV header 的 Python 代码?

转载 作者:行者123 更新时间:2023-11-29 08:35:55 25 4
gpt4 key购买 nike

这些值本质上是 CSV 中的堆叠列,它们都出现在同一列中。为了让我辨别一个值属于哪个 header ,我几乎只是说“它可以变成一个数字”。

我在 Python 中尝试做的最简单的例子:

data = ["a","1","2","3","b","4","5","6","c","7","8","9"]

class treatment:
def __init__(self, name):
self.name = name
self.data = []

results = []

for d in data:
try:
int(d)
except ValueError:
results.append(treatment(name=d))
else:
results[-1].data.append(d)

这是我在 Rust 中拥有的,但是在解析后不起作用:

extern crate csv;

use std::error::Error;
use std::fs::File;
use std::io;
use std::prelude::v1::Option;
use std::process;
use std::vec::Vec;

struct Treatment {
raw_name: String,
channel: String,
data: Vec<i64>,
}

impl Treatment {
fn observe(&mut self, observation: i64) {
&mut self.data.push(observation);
}
}

struct Experiment {
treatments: Vec<Treatment>,
}

impl Experiment {
fn add_treatment(&mut self, treatment_name: &str, channel: &str) {
&mut self.treatments.push(Treatment {
raw_name: treatment_name.to_string(),
channel: channel.to_string(),
data: Vec::new(),
});
}

fn get_current_experiment(&mut self) -> &Treatment {
self.treatments.last().unwrap()
}
}

fn deserialize_csv(file_path: String) -> csv::Reader<File> {
csv::ReaderBuilder::new()
.has_headers(false)
.from_path(file_path)
.expect("Experienced issues reading csv file")
}

fn vectorize_string_records(mut csv_reader: csv::Reader<File>) {
let mut experiments: Experiment = Experiment {
treatments: Vec::new(),
};

for row in csv_reader.records() {
// for these datasets we only care about data in the first cell
let datapoint = match &row {
Ok(T) => T.get(0),
Err(E) => Some(""),
}.unwrap();

let val_as_int = datapoint.parse::<i64>();

let current_treatment = experiments.get_current_experiment();

// discern if value is header or datapoint
match val_as_int {
Ok(int_val) => &current_treatment.observe(int_val),
Err(new_header) => &experiments.add_treatment(datapoint, &"ch=1".to_string()),
};

println!("{}", datapoint);
}
}

fn main() {
let i = deserialize_csv("/home/file.csv".to_string());
vectorize_string_records(i);
}

在尝试用 Rust 实现它时,我在一些概念上遇到了困难。

最佳答案

将您的 Python 代码直接移植到 Rust:

#[derive(Debug)]
struct Treatment {
name: String,
data: Vec<i32>,
}

impl Treatment {
fn new(name: String) -> Self {
Self {
name,
data: Vec::new(),
}
}
}

fn main() {
let data = ["a", "1", "2", "3", "b", "4", "5", "6", "c", "7", "8", "9"];
let mut results: Vec<Treatment> = Vec::new();
for d in &data {
if let Ok(n) = d.parse::<i32>() {
let last = results
.last_mut()
.expect("Some header must come before the values");
last.data.push(n);
} else {
results.push(Treatment::new(d.to_string()))
}
}
println!("results = {:#?}", results);
}

Playground

关于rust - 我如何通过询问 "can it be turned into a number"来移植识别值属于哪个 CSV header 的 Python 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52250069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com