python - 字符串中最常见的字母

标签 python python-3.x

完成一项练习,查找字符串中最常见的字母(不包括标点符号),结果应为小写。因此,在示例中 "HHHHello World!!!!!!!!!!" 结果应为 "h"

到目前为止我所拥有的是:

text=input('Insert String: ')
def mwl(text):
    import string
    import collections
    for p in text:
        p.lower()
    for l in string.punctuation:
        for x in text:
            if x==l:
                text.replace(x,'')
    collist=collections.Counter(text).most_common(1)
    print(collist[0][0])

mwl(text)

非常感谢您帮助理解原因:

  1. text 中大小写并未更改为较低
  2. 标点符号不会从文本字符串中永久删除

最佳答案

有几个问题:

  • 字符串是不可变的。这意味着 lower()replace() 等函数返回结果并保留原始字符串不变。您需要将该返回值分配到某处。

  • lower()可以对整个字符串进行操作:text = text.lower()

有关如何从字符串中删除标点符号的一些想法,请参阅 Best way to strip punctuation from a string in Python

关于python - 字符串中最常见的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27694014/

相关文章:

python-3.x - jinja/ansible 将字符串转换为 bool 值

python - Django - 即使链接有效,测试也会失败

Django Postgres 不区分大小写的文本字段和 citext

python - 时间比应有的要快

python - 在 python 日志文件中包含当前日期

python - 如何在 Django 的基于类的 View 中对方法进行单元测试?

python - 如何使用 Python 3 仅使用内置模块上传大文件?

python - 从 FTP 检索文件时如何指定本地目标文件夹

python - python 中 main 中的其他模块无法识别 input()

python - django.setup() 的目的是什么?