Python代码,用于计算单词中字母的重复次数

2024-10-04 11:32:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要你帮助计算单词中字母的重复次数

Input (string): HelloWorld
Output: H1e1l3o2W1r1d1  

Tags: inputoutputstring字母单词次数helloworldh1e1l3o2w1r1d1
3条回答

使用string.count()

语法如下:

string.count(substring, [start_index],[end_index])

substring是您试图查找的字母,[start_index]是开始搜索的字母(请记住,python在使用索引时从0开始),而[end_index]是停止搜索的字母

正如其他人提到的,您可以使用str.count()。一种简单的方法是看第一个字母,数一数,然后从字符串中删除它的所有实例并重复。简单的递归答案可能如下所示:

def count(word):
    if len(word) == 0:
        return ""
    return word[0]+str(word.count(word[0]))+count(word[1:].replace(word[0], ""))

您需要输入一个运行长度编码算法

Geeksforgeks在这方面有一篇很棒的文章:

https://www.geeksforgeeks.org/run-length-encoding-python/

# Python code for run length encoding 
from collections import OrderedDict 
def runLengthEncoding(input): 
  
    # Generate ordered dictionary of all lower 
    # case alphabets, its output will be  
    # dict = {'w':0, 'a':0, 'd':0, 'e':0, 'x':0} 
    dict=OrderedDict.fromkeys(input, 0) 
  
    # Now iterate through input string to calculate  
    # frequency of each character, its output will be  
    # dict = {'w':4,'a':3,'d':1,'e':1,'x':6} 
    for ch in input: 
        dict[ch] += 1
  
    # now iterate through dictionary to make  
    # output string from (key,value) pairs 
    output = '' 
    for key,value in dict.items(): 
         output = output + key + str(value) 
    return output 
   
# Driver function 
if __name__ == "__main__": 
    input="wwwwaaadexxxxxx"
    print (runLengthEncoding(input))

输出:

'w4a3d1e1x6'

你的例子是:

input = 'hello world'
print(runLengthEncoding(input))

输出:

'h1e1l3o2 1w1r1d1'

这正是你想要的

以上代码来自Geeksforgeks链接

相关问题 更多 >