Rust : 红楼梦一书中文字符的统计

释放双眼,带上耳机,听听看~!

一、准备工作

1、相关的库

因为红书中大部分是中文字符,标准库中目前还无法直接处理。因此,在进行分析前,在toml文件中的依赖库中,添加一下以下:


1
2
1encoding = "0.2"
2

具体可参考以下资料:


1
2
1https://github.com/lifthrasiir/rust-encoding
2

2、红楼梦一书的txt文件。直接找度娘。

二、相关代码


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1extern crate encoding;
2use encoding::{Encoding, DecoderTrap};
3use encoding::all::GB18030; //可以转成汉字的字库
4fn main() {
5    let mut f = File::open("C:\\Users\\Desktop\\redstory.txt")
6        .ok()
7        .expect("file read error!");
8    let mut hp: HashMap<char, i32> = HashMap::new();
9    let mut reader: Vec<u8> = Vec::new();//u8集
10    f.read_to_end(&mut reader).ok().expect("can not read file");
11    let mut content = String::new();//字符串
12    GB18030.decode_to(&mut reader, DecoderTrap::Ignore, &mut content);
13    for c in content.chars() {
14        let counter = hp.entry(c).or_insert(0);
15        *counter += 1;
16    }
17    println!("hp:{:?}", hp);
18}
19

或main{}中以下代码可以改一下:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1extern crate encoding;
2use encoding::{Encoding, DecoderTrap};
3use encoding::all::GB18030; //可以转成汉字的字库
4fn main() {
5    let mut f = File::open("C:\\Users\\Desktop\\redstory.txt")
6        .ok()
7        .expect("file read error!");
8    let mut reader: Vec<u8> = Vec::new();
9    let mut hp: HashMap<char, i32> = HashMap::new();
10    f.read_to_end(&mut reader).ok().expect("can not read file");
11    let content:String = GB18030.decode(&reader, DecoderTrap::Strict).unwrap();
12    for d in content.chars() {
13        let counter = hp.entry(d).or_insert(0);
14        *counter += 1;
15    }
16    println!("hp :{:?}", hp);
17}
18

你可以看到不同字符串出现的频率了。

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++遍历文件夹

2022-1-11 12:36:11

安全资讯

柳叶刀:大幅缩短新冠患者排毒时间的疗法出现

2020-5-12 11:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索