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

标签 python r string

目前,我有一个字符串"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 ... 

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

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

但是,对于下一步要做什么,我有点不知所措。有人可以启发我吗?非常感谢。

最佳答案

在 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 

并稍微扩展一下以处理多个单词和/或大写字母的可能性:

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

关于python - 将单词中的字母频率与 R(或 python)中的 26 个字母进行匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28104250/

相关文章:

javascript - Harvest's Chosen 可以与 Python Pyramid 框架一起使用吗?

javascript - 更改数据表中的列过滤器 "All"标签

c - 在 C 中创建字符串的不同方法

java - 如何使用 Strings.xml 更改文本值 - AndroidX

python - 在tox+pytest中使用自己的包

python - 使用 pandas 2 比较两列

python - flask +异步

r - 为什么 xgboost 不绘制我的树?

在生成箱线图时提醒 R 整数是一个因素

c# - 从 Url 中获取子字符串