generated from ElnuDev/rust-project
parent
23dfa06d15
commit
359c46d776
|
@ -1,5 +1,5 @@
|
|||||||
use renrs;
|
use renrs;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
renrs::hello();
|
renrs::parse("demo.csv");
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,9 @@
|
|||||||
|
// + indicates one or more times
|
||||||
|
field = { (ASCII_DIGIT | "." | "-")+ }
|
||||||
|
// ~ indicates directly followed by
|
||||||
|
// * indicates zero or more times (optional)
|
||||||
|
record = { field ~ ("," ~ field)* }
|
||||||
|
// SOI - start of input
|
||||||
|
// END - end of input
|
||||||
|
// There may be trailing newlines at the end
|
||||||
|
file = { SOI ~ (record ~ ("\r\n" | "\n"))* ~ "\n"* ~ EOI }
|
@ -1,3 +1,35 @@
|
|||||||
pub fn hello() {
|
use std::fs;
|
||||||
println!("Hello, world!");
|
|
||||||
|
use pest::Parser;
|
||||||
|
use pest_derive::Parser;
|
||||||
|
|
||||||
|
#[derive(Parser)]
|
||||||
|
#[grammar = "csv.pest"]
|
||||||
|
struct CSVParser;
|
||||||
|
|
||||||
|
pub fn parse(file_path: &str) {
|
||||||
|
let unparsed_file = fs::read_to_string(file_path).expect("cannot find file");
|
||||||
|
let file = CSVParser::parse(Rule::file, &unparsed_file)
|
||||||
|
.expect("unsuccessful parse") // unwrap the parse result
|
||||||
|
.next().unwrap(); // get and unwrap the `file` rule; never fails
|
||||||
|
|
||||||
|
let mut field_sum = 0.0;
|
||||||
|
let mut record_count: u64 = 0;
|
||||||
|
|
||||||
|
for record in file.into_inner() {
|
||||||
|
match record.as_rule() {
|
||||||
|
Rule::record => {
|
||||||
|
record_count += 1;
|
||||||
|
|
||||||
|
for field in record.into_inner() {
|
||||||
|
field_sum += field.as_str().parse::<f64>().unwrap();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Rule::EOI => (),
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("Sum of fields: {field_sum}");
|
||||||
|
println!("Number of records: {record_count}");
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in new issue