【问题标题】:Python code to count the recurrence of a letter in a wordPython代码计算单词中字母的重复次数
【发布时间】:2020-06-22 16:22:35
【问题描述】:

我需要你的帮助来计算单词中某个字母的出现频率。

Input (string): HelloWorld
Output: H1e1l3o2W1r1d1  

【问题讨论】:

  • 你尝试过什么,它到底有什么问题?
  • 请注意Stack Overflow 不是代码编写服务。我们可以帮助解决特定的技术问题,而不是对代码或建议的开放式请求。请edit您的问题以显示您到目前为止所做的尝试,以及您需要帮助的具体问题。有关如何帮助我们帮助您的详细信息,请参阅How to Ask 页面。

标签: python count recurrence


【解决方案1】:

您需要对输入进行游程编码算法。

GeeksforGeeks 对此有一篇很棒的文章:

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'

正是你想要的。

以上代码来自 GeeksforGeeks 链接。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      使用string.count()

      语法如下:

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

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

      【讨论】:

        【解决方案4】:

        我认为这个函数应该可以解决问题:

        def countoccurences(word, character):
            occuresin =[]
            for letter in word:
                if letter == character:
                    occuresin.append(letter)
                
            print("Letter", character, " occurs in string: ", str(len(occuresin)), " times.")
            return len(occuresin)
        
        countoccurences("1se3sr4g45h7e5q3e", 'e')
        

        【讨论】:

        • @datageek 对不起,你为什么不加任何解释地回答我?
        • 这没有回答问题。它提供的是str.count 的低级实现,例如"1se3sr4g45h7e5q3e".count('e').
        • 那么您应该更好地解释您的问题,因为现在我们可以解释您想要实现的目标。
        • 请注意,我注意到提问者。问题清楚地表明,对于输入 HelloWorld,所需的输出是 H1e1l3o2W1r1d1
        • 对不起。然后我想我完全误解了一切,但我相信已经发布了正确的答案。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-10
        • 1970-01-01
        • 2017-10-22
        • 2020-11-16
        • 2011-06-01
        相关资源
        最近更新 更多