【问题标题】:Match letter frequency within a word against 26 letters in R (or python)将单词中的字母频率与 R(或 python)中的 26 个字母匹配
【发布时间】:2015-01-23 06:31:19
【问题描述】:

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

但是,对于下一步该做什么,我有点困惑。有人可以启发我吗?非常感谢。

【问题讨论】:

    标签: python r string


    【解决方案1】:

    在 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
    

    【讨论】:

    • 谢谢乔希,这是一个很好的下一步。只是想知道您是否还会知道如何将表函数的输出更改为包含单词中未出现的字母的 0 频率。
    • table(factor(strsplit("abdicator", "")[[1]], levels = letters))
    • 嗨乔希,这是钱。非常感谢:)
    【解决方案2】:

    在 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]
    

    或者:

    >>> 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]
    

    【讨论】:

    • 非常感谢约翰。这正是我所追求的。
    【解决方案3】:

    Python:

    import collections
    import string
    
    counts = collections.Counter('abdicator')
    chars = string.ascii_lowercase
    print(*chars, sep=' ')
    print(*[counts[char] for char in chars], sep=' ')
    

    【讨论】:

    • 这段代码打印了一个大的未终止行,并且没有使用它导入的string 模块。
    【解决方案4】:

    在 Python 2 中:

    import string, collections
    ctr = collections.Counter('abdicator')
    for l in string.ascii_lowercase:
        print l,
    print
    for l in string.ascii_lowercase:
        print ctr[l],
    print
    

    在 Python 3 中,只有 print 的语法发生了变化。

    这会产生您要求的输出。核心思想是collections.Counter,用缺少的键索引,谦虚地返回0,其明显的语义“此键已被看到0次”与它用于存在的键的语义完全一致(它返回的地方他们的计数,即他们被看到的次数)。

    【讨论】:

      猜你喜欢
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 2017-10-09
      • 2018-08-30
      • 2022-11-22
      相关资源
      最近更新 更多