python - 计算单词列表中的字母频率,不包括同一个单词中的重复项

标签 python algorithm

我正在尝试查找单词列表中出现频率最高的字母。我在算法上苦苦挣扎,因为我只需要计算一个单词中的字母频率一次跳过重复项,所以我需要帮助找到一种方法来计算整个列表中字母的频率,每个单词只出现一次,忽略第二次出现。

例如,如果我有:

words = ["tree", "bone", "indigo", "developer"]

频率为:

letters={a:0, b:1, c:0, d:2, e:3, f:0, g:1, h:0, i:1, j:0, k:0, l:1, m:0, n:2, o:3, p:1, q:0, r:2, s:0, t:1, u:0, v:1, w:0, x:0, y:0, z:0}

从字母字典中可以看出:'e' 是 3 而不是 5,因为如果 'e' 在同一个单词中重复多次,它应该被忽略。

这是我想出的算法,它是用 Python 实现的:

for word in words:
    count=0;

    for letter in word:
        if(letter.isalpha()):
            if((letters[letter.lower()] > 0  && count == 0) ||
               (letters[letter.lower()] == 0 && count == 0)):

                    letters[letter.lower()]+=1
                    count=1

            elif(letters[letter.lower()]==0 && count==1):   
                letters[letter.lower()]+=1

但这仍然需要工作,我想不出其他任何事情,我会很高兴有人能帮助我考虑一个可行的解决方案。

最佳答案

不使用更新的@Primusa 答案的变体:

from collections import Counter

words = ["tree", "bone", "indigo", "developer"]
counts = Counter(c for word in words for c in set(word.lower()) if c.isalpha())

输出

Counter({'e': 3, 'o': 3, 'r': 2, 'd': 2, 'n': 2, 'p': 1, 'i': 1, 'b': 1, 'v': 1, 'g': 1, 'l': 1, 't': 1})

基本上将每个单词转换为一个集合,然后对每个集合进行迭代。

关于python - 计算单词列表中的字母频率,不包括同一个单词中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54223703/

相关文章:

python - 使用内联其他函数编译带有函数的 Numba 模块时出错

python - Windrose 图中的子图

java - 外壳排序 : won't work with certain combos of intervals

c - 使用交替的最小值和最大值对数组进行排序

sql - 如何在 SQL Server 中使用存储过程合并第三个表中的两个数据表?

python - 将 python 脚本编译为 C 时如何修复 Cython header 错误

python - 带有打开端口扫描器按钮的 GUI

c++ - 从堆中移除元素

python - 将自定义函数添加到 Python 中的现有类中

algorithm - 找到可能的不同非递减数组的总数