【问题标题】:How to fix the appearance of unexpected characters in string counts如何修复字符串计数中出现意外字符的问题
【发布时间】:2020-11-27 21:37:44
【问题描述】:

此代码按字母顺序打印字符串中出现的字母表以及每个字母出现的次数。此代码中有两个不需要的数字,即 8 和 .1,但我不知道如何从输出中删除它们。

 s = 'ThiS is String with Upper and lower case Letters.'

 # Or see Python's Counter class: counts = Counter(s.lower())
counts = {}
for c in s.lower():
    counts[c] = counts.get(c, 0) + 1

for c, n in sorted(counts.items()):
    print(c, n)

【问题讨论】:

  • 8 是字符串中“”的空格数。
  • 那我猜“1”代表点(.)。
  • 我不希望在输出中出现这种情况,哈哈。我怎样才能改变它,使这两个数字不显示?

标签: python python-3.x


【解决方案1】:

纯粹是为了好玩……如果你真的想的话,你可以用两行来完成。 :-)

字符串:

 s = 'ThiS is String with Upper and lower case Letters.'

荒谬:

chars = [i for i in s.lower() if i.isalpha()]
print(*sorted({c: chars.count(c) for c in chars}.items(), key=lambda x: x[1], reverse=True), sep='\n')

输出:

('t', 5)
('s', 5)
('e', 5)
('i', 4)
('r', 4)
('h', 2)
('n', 2)
('w', 2)
('p', 2)
('a', 2)
('l', 2)
('g', 1)
('u', 1)
('d', 1)
('o', 1)
('c', 1)

【讨论】:

    【解决方案2】:

    所以,您可以从输入字符串中删除spacesdots

    s = 'ThiS is String with Upper and lower case Letters.'
    
    s=s.replace(" ","").replace(".","")# remove spaces and dots from the input string
    
    counts = {}
    for c in s.lower():
        counts[c] = counts.get(c, 0) + 1
    
    for c, n in sorted(counts.items()):
        print(c, n)
    

    [输出]:

    a 2
    c 1
    d 1
    e 5
    g 1
    h 2
    i 4
    l 2
    n 2
    o 1
    p 2
    r 4
    s 5
    t 5
    u 1
    w 2
    

    【讨论】:

    • 不用链接replaces,你可以用更pythonic的方式做到这一点:s = "".join(c for c in s if c.isalpha())
    【解决方案3】:

    看起来它也在计算字符串中的空格和句点。将它们替换为 "" 是解决此问题的简单方法。

    【讨论】:

      【解决方案4】:
      import string
      from collections import Counter
      s = "".join(filter(lambda c: c in string.ascii_letters, s))
      for c, count in Counter(s).items():
          print(c, count)
      

      【讨论】:

        【解决方案5】:

        您可以使用str.count() 简单地计算它们,并简单地检查isalpha()

        s = 'ThiS is String with Upper and lower case Letters. 81'
        {char: s.count(char) for char in s.lower() if char.isalpha()}
        

        结果:

        {'t': 4,
         'h': 2,
         'i': 4,
         's': 3,
         'r': 4,
         'n': 2,
         'g': 1,
         'w': 2,
         'u': 0,
         'p': 2,
         'e': 5,
         'a': 2,
         'd': 1,
         'l': 1,
         'o': 1,
         'c': 1}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-12-02
          • 1970-01-01
          • 2012-10-03
          • 2011-04-29
          • 2022-01-01
          • 1970-01-01
          相关资源
          最近更新 更多