【问题标题】:Counting number of occurrences in a string计算字符串中出现的次数
【发布时间】:2021-04-17 14:30:57
【问题描述】:

我需要返回一个字典,计算预定列表中每个字母出现的次数。问题是我需要将大写和小写字母都计算为相同,所以我不能使用 .lower 或 .upper。

因此,例如,如果“t”是要搜索的字母,“这是一个 Python 字符串”应该返回 {'t':3}。

这是我目前所拥有的......

def countLetters(fullText, letters):
    countDict = {i:0 for i in letters}
    lowerString = fullText.lower()
    for i in lowerString:
        if i in letters:
            countDict[i] += 1

    return countDict

'letters' 是条件,fullText 是我要搜索的字符串。

这里明显的问题是,如果测试是“T”而不是“t”,我的代码将不会返回任何内容抱歉我的术语中有任何错误,我对此很陌生。任何帮助将不胜感激!

【问题讨论】:

  • 你说不能用.lower,为什么还要用呢?
  • collections 标准库为此提供了 Counter 类
  • 循环应该是for i in lowerString:
  • 我不确定我是否理解这段代码的问题所在。能否请您出示minimal reproducible example
  • 我使用 .lower 是因为他第一次没有说明我们不应该使用它。他再次向我们提出问题,这次检查大写的附加条件以确保我们不使用 .lower 或 .upper

标签: python string dictionary count


【解决方案1】:

要忽略大小写,您需要输入 = 输入 = input.lower () . 使用列表操作列出输入文本的所有字符。 如果您扫描空格字符,它也可以用作单词计数器。

input = "Batuq batuq BatuQ" # Reads all inputs up to the EOF character

input = input.replace('-',' ')#Replace (-, + .etc) expressions with a space character.
input = input.replace('.','')
input = input.replace(',','')
input = input.replace("`",'')
input = input.replace("'",'')

#input= input.split(' ') #if you use it, it will sort by the most repetitive words
dictionary = dict()
count = 0
for word in input:
    dictionary[word] = input.count(word)
    
print(dictionary)

#Writes the 5 most repetitive characters
for k in sorted(dictionary,key=dictionary.get,reverse=True)[:5]:
    print(k,dictionary[k])

【讨论】:

    【解决方案2】:

    这样的东西能同时处理区分大小写的字母计数和不区分大小写的计数吗?

    from typing import List
    
    def count_letters(
        input_str: str,
        letters: List[str],
        count_case_sensitive: bool=True
    ):
        """
        count_letters consumes a list of letters and an input string
        and returns a dictionary of counts by letter. 
        """
        if count_case_sensitive is False:
            input_str = input_str.lower()
            letters = list(set(map(lambda x: x.lower(), letters)))
        # dict comprehension - build your dict in one line
        # Tutorial on dict comprehensions: https://www.datacamp.com/community/tutorials/python-dictionary-comprehension
        counts = {letter: input_str.count(letter) for letter in letters}
     
        return counts
    
    # define function inputs    
    letters = ['t', 'a', 'z', 'T']
    string = 'this is an example with sTrings and zebras and Zoos'
    
    # case sensitive
    count_letters(
        string,
        letters,
        count_case_sensitive=True
    )
    # {'t': 2, 'a': 5, 'z': 1, 'T': 1}
    
    # not case sensitive
    count_letters(
        string,
        letters,
        count_case_sensitive=False
    )
    # {'a': 5, 'z': 2, 't': 3} # notice input T is now just t in dictionary of counts
    

    【讨论】:

      【解决方案3】:

      试试看 - 像这样:

      def count_letters(fullText, letters):
          countDict = {i: 0 for i in letters}
          lowerString = fullText.lower()
          for i in lowerString:
              if i in letters:
                  countDict[i] += 1
          return countDict
      
      test = "This is a Python string."
      print(count_letters(test, 't')) #Output: 3
      

      【讨论】:

      • 对不起,我最初发布问题时打错了。我事先把它弄乱了,试图让它工作并改变我的代码。那是我原来上交的代码,问题是当test是“T”的时候,什么都没有返回
      【解决方案4】:

      您正在循环错误的字符串。您需要循环遍历lowerString,而不是fullString,因此在计数时忽略大小写。

      if i in countDict 也比if i in letter 更有效。

      def countLetters(fullText, letters):
          countDict = {i.lower():0 for i in letters}
          lowerString = fullText.lower()
          for i in lowerString:
              if i in countDict:
                  countDict[i] += 1
      
          return countDict
      

      【讨论】:

      • 感谢您的帮助!我试过了,但问题是当测试是“T”时,它不会返回任何东西。由于 .lower 它似乎只接受小写测试。那是我迷路的地方,我想不出一种方法来测试小写和大写是否为同一个字母
      • letters上也使用.lower()
      【解决方案5】:

      你可以做的就是简单地复制大写和小写的字典,如下所示:

      def countLetters(fullText, letters):
          countDict = {}
          for i in letters:
              countDict[i.upper()]=0
              countDict[i.lower()]=0
          lowerString = fullText.lower()
          letters = letters.lower()
          for i in lowerString:
              if i in letters:
                  countDict[i] += 1
                  if (i!=i.upper()):
                      countDict[i.upper()] +=1
      
          return countDict
      print(countLetters("This is a Python string", "TxZY"))
      

      现在您还可以做的一些事情是遍历原始字符串并将countDict[i] += 1 更改为countDict[i.lower()] +=1

      【讨论】:

      • 这非常接近我需要完成的工作,但它在字典中分别返回大写字母和小写字母,我需要将它们视为同一个字母。 {'A':45,'a':45,'E':44,'e':44,'I':32,'i':32,'O':29,'o':29,'你':12,'你':12}
      • 这实际上应该可以实现您的要求。尽管它们是“独立的”,但它们具有相同的值。
      • 理论上可以,但其中一项测试是字典的长度,因此它只能返回所要求的特定值。所以对于第一个测试,'aeiou',它只能返回这五个结果。如果我返回大写和小写,我会通过测试
      【解决方案6】:

      使用集合模块中的计数器

      from collections import Counter
      input = "Batuq batuq BatuQ"
      bow=input.split(' ')
      results=Counter(bow)
      print(results)
      

      输出: Counter({'Batuq': 1, 'batuq': 1, 'BatuQ': 1})

      【讨论】:

        猜你喜欢
        • 2014-04-24
        • 1970-01-01
        • 2012-06-24
        • 2020-02-21
        • 2012-02-12
        • 2023-02-04
        相关资源
        最近更新 更多