将单词中的字母频率与R(或python)中的26个字母匹配

C. *_*eng 2 python string r

目前,我有一个字符串"abdicator".我想找出这个词的字母频率与所有英文字母(即26个字母)的比较,其输出形式如下.

输出:

a b c d e f g h i ... o ... r s t ... x y z
2 1 1 0 0 0 0 0 1..0..1..0..1 0 1 ... 0 ... 
Run Code Online (Sandbox Code Playgroud)

此输出可以是数字向量(名称为26个字母).我最初的尝试是首先使用strsplit函数将字符串拆分成单个字母(使用R):

strsplit("abdicator","") #split at every character
#[[1]]
#[1] "a" "b" "c" "d" "e"`
Run Code Online (Sandbox Code Playgroud)

但是,对于下一步该怎么做,我有点困惑.请有人赐教我吗?非常感谢.

Jos*_*ien 8

在R:

table(c(letters, strsplit("abdicator", "")[[1]]))-1
# a b c d e f g h i j k l m n o p q r s t u v w x y z 
# 2 1 1 1 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 0 
Run Code Online (Sandbox Code Playgroud)

并延伸一点来处理多个单词和/或大写字母的可能性:

words <- c("abdicator", "Syzygy")
letterCount <- function(X) table(c(letters, strsplit(tolower(X), "")[[1]]))-1
t(sapply(words,  letterCount))
#           a b c d e f g h i j k l m n o p q r s t u v w x y z
# abdicator 2 1 1 1 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 0
# syzygy    0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 3 1
Run Code Online (Sandbox Code Playgroud)

  • 或者`table(因子(strsplit("abdicator","")[[1]],levels = letters))` (4认同)

Joh*_*nck 6

在Python中:

>>> from collections import Counter
>>> s = "abdicator"
>>> Counter(s)
Counter({'a': 2, 'c': 1, 'b': 1, 'd': 1, 'i': 1, 'o': 1, 'r': 1, 't': 1})
>>> map(Counter(s).__getitem__, map(chr, range(ord('a'), ord('z')+1)))
[2, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)

要么:

>>> import string
>>> map(Counter(s).__getitem__, string.lowercase)
[2, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)