我有一个名为的电子书文本文件Frankenstein.txt,我想知道小说中每个字母使用了多少次。
我的设置:
我像这样导入了文本文件以获得字符向量 character_array
string <- readChar("Frankenstein.txt", filesize)
character_array <- unlist(strsplit(string, ""))
Run Code Online (Sandbox Code Playgroud)
character_array 给我这样的东西。
"F" "r" "a" "n" "k" "e" "n" "s" "t" "e" "i" "n" "\r", ...
Run Code Online (Sandbox Code Playgroud)
我的目标:
我想获取文本文件中每次出现字符的次数。换句话说,我想计算每个unique(character_array)
[1] "F" "r" "a" "n" "k" "e" "s" "t" "i" "\r" "\n" "b" "y" "M"
[15] " " "W" "o" "l" "c" "f" "(" "G" "d" "w" ")" "S" "h" "C"
[29] "O" "N" "T" "E" "L" "1" "2" "3" "4" "p" "5" "6" "7" "8"
[43] "9" "0" "_" "." "v" "," "g" "P" "u" "D" "—" "Y" "j" "m"
[57] "I" "z" "?" ";" "x" "q" "B" "U" "’" "H" "-" "A" "!" ":"
[71] "R" "J" "“" "”" "æ" "V" "K" "[" "]" "‘" "ê" "ô" "é" "è"
Run Code Online (Sandbox Code Playgroud)
我的尝试
当我打电话时,plot(as.factor(character_array))我得到了一个很好的图表,它在视觉上给了我我想要的东西。
但是,我需要获取每个字符的确切值。我想要类似二维数组的东西:
[,1] [,2] [,3] [,4] ...
[1,] "a" "A" "b" "B" ...
[2,] "1202" "50" "12" "9" ...
Run Code Online (Sandbox Code Playgroud)
制作此类文本处理管道的一种好方法是使用magrittr::%>%
管道。这是一种方法,假设您的文本在"frank.txt"(有关每个步骤的解释,请参见底部):
library(magrittr)
# read the text in
frank_txt <- readLines("frank.txt")
# then send the text down this pipeline:
frank_txt %>%
paste(collapse="") %>%
strsplit(split="") %>% unlist %>%
`[`(!. %in% c("", " ", ".", ",")) %>%
table %>%
barplot
Run Code Online (Sandbox Code Playgroud)
请注意,您可以停在table()并将结果分配给一个变量,然后您可以根据需要对其进行操作,例如通过绘制它:
char_counts <- frank_txt %>% paste(collapse="") %>%
strsplit(split="") %>% unlist %>% `[`(!. %in% c("", " ", ".", ",")) %>%
table
barplot(char_counts)
Run Code Online (Sandbox Code Playgroud)
您还可以将表格转换为数据框,以便以后更轻松地操作/绘图:
counts_df <- data.frame(
char = names(char_counts),
count = as.numeric(char_counts),
stringsAsFactors=FALSE)
head(counts_df)
## char count
## a 13
## b 2
## c 7
## d 5
## e 24
## f 6
Run Code Online (Sandbox Code Playgroud)
每一步解释:这是完整的管道链,每一步解释:
# going to send this text down a pipeline:
frank_txt %>%
# combine lines into a single string (makes things easier downstream)
paste(collapse="") %>%
# tokenize by character (strsplit returns a list, so unlist it)
strsplit(split="") %>% unlist %>%
# remove instances of characters you don't care about
`[`(!. %in% c("", " ", ".", ",")) %>%
# make a frequency table of the characters
table %>%
# then plot them
barplot
Run Code Online (Sandbox Code Playgroud)
请注意,这完全等同于以下可怕的(“可怕的”?!?!)代码——前向管道%>%只是将其右侧的函数应用于其左侧的值(并且.是代词,指代左侧的值) ;见介绍小插图):
barplot(table(
unlist(strsplit(paste(frank_txt, collapse=""), split=""))[
!unlist(strsplit(paste(frank_txt, collapse=""), split="")) %in%
c(""," ",".",",")]))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5221 次 |
| 最近记录: |