我正在尝试重新学习数据--生锈科学。
我有一个Vec<String>,其中包括一个分隔符“AC.26”和一个新行"!end“。
我想要结束的是Vec<Vec<String>>,它可以放在一个2D ND数组中。
我有一个python代码:
file = open('somefile.dat')
lst = []
for line in file:
lst += [line.split('|')]
df = pd.DataFrame(lst)
SAMV2FinalDataFrame = pd.DataFrame(lst,columns=column_names)我在这里用铁锈再造了它:
fn lines_from_file(filename: impl AsRef<Path>) -> Vec<String> {
let file = File::open(filename).expect("no such file");
let buf = BufReader::new(file);
buf.lines()
.map(|l| l.expect("Could not parse line"))
.collect()
}
fn main() {
let lines = lines_from_file(".dat");
let mut new_arr = vec![];
//Here i get a lines immitable borrow
for line in lines{
new_arr.push([*line.split("!end")]);
}
// here i get expeected closure found str
let x = lines.split("!end");
let array = Array::from(lines)我所拥有的:'1','1','1','1','2','2','2','2','2',‘2’,‘2’,‘2’,‘2’,‘2’,‘2’,‘2’,‘2’,‘2’,‘2’,‘2’,‘2’
编辑:为什么当我的涡轮鱼,它会使它消失在堆栈溢出?
发布于 2022-02-18 20:24:13
我认为,您遇到的部分问题是如何处理数组的。例如,Vec::push只添加一个元素,因此您需要使用Vec::extend。我还遇到了一些空字符串,因为"!end"的拆分会在子字符串的末端留下尾随的'|'。错误是相当奇怪的,我不完全确定结束是从哪里来的。
let lines = vec!["1|1|1|!end|2|2|2|!end".to_string()];
let mut new_arr = Vec::new();
// Iterate over &lines so we don't consume lines and it can be used again later
for line in &lines {
new_arr.extend(line.split("!end")
// Remove trailing empty string
.filter(|x| !x.is_empty())
// Convert each &str into a Vec<String>
.map(|x| {
x.split('|')
// Remove empty strings from ends split (Ex split: "|2|2|2|")
.filter(|x| !x.is_empty())
// Convert &str into owned String
.map(|x| x.to_string())
// Turn iterator into Vec<String>
.collect::<Vec<_>>()
}));
}
println!("{:?}", new_arr);我还想出了另一个版本,可以更好地处理您的用例。前面的方法删除了所有空字符串,而这个方法应该在正确处理"!end"时保留它们。
use std::io::{self, BufRead, BufReader, Read, Cursor};
fn split_data<R: Read>(buffer: &mut R) -> io::Result<Vec<Vec<String>>> {
let mut sections = Vec::new();
let mut current_section = Vec::new();
for line in BufReader::new(buffer).lines() {
for item in line?.split('|') {
if item != "!end" {
current_section.push(item.to_string());
} else {
sections.push(current_section);
current_section = Vec::new();
}
}
}
Ok(sections)
}在本例中,我使用Read进行更简单的测试,但它也可以处理一个文件。
let sample_input = b"1|1|1|!end|2|2|2|!end";
println!("{:?}", split_data(&mut Cursor::new(sample_input)));
// Output: Ok([["1", "1", "1"], ["2", "2", "2"]])
// You can also use a file instead
let mut file = File::new("somefile.dat");
let solution: Vec<Vec<String>> = split_data(&mut file).unwrap();https://stackoverflow.com/questions/71178927
复制相似问题