generated from ElnuDev/rust-project
parent
23dfa06d15
commit
359c46d776
5 changed files with 51 additions and 3 deletions
|
@ -7,3 +7,5 @@ edition = "2021"
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
pest = "2.6.0"
|
||||||
|
pest_derive = "2.6.0"
|
||||||
|
|
5
demo/demo.csv
Normal file
5
demo/demo.csv
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
65279,1179403647,1463895090
|
||||||
|
3.1415927,2.7182817,1.618034
|
||||||
|
-40,-273.15
|
||||||
|
13,42
|
||||||
|
65537
|
|
|
@ -1,5 +1,5 @@
|
||||||
use renrs;
|
use renrs;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
renrs::hello();
|
renrs::parse("demo.csv");
|
||||||
}
|
}
|
||||||
|
|
9
src/csv.pest
Normal file
9
src/csv.pest
Normal file
|
@ -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 }
|
36
src/lib.rs
36
src/lib.rs
|
@ -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…
Add table
Reference in a new issue