字符串中最常见的字母

2024-10-01 04:53:50 发布

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

完成一个练习,找出字符串中最常见的字母,不包括标点符号,结果应该是小写。所以在示例"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. 不会从text字符串中永久删除标点符号

Tags: 字符串textinimport示例forworldstring
3条回答

你可以试试这个:

>>> import re
>>> from collections import Counter
>>> my_string = "HHHHello World!!!!!!!!!!"
>>> Counter("".join(re.findall("[a-z]+",my_string.lower()))).most_common(1)
[('h', 4)]
text = input('Insert String: ')

from string import punctuation
from collections import Counter
def mwl(text):
    st = set(punctuation)
    # remove all punctuation and make every letter lowercase
    filtered = (ch.lower() for ch in text if ch not in st)
    # make counter dict from remaining letters and return the most common
    return Counter(filtered).most_common()[0][0]

或使用str.翻译删除标点:

^{pr2}$

使用您自己的代码,您需要将文本重新分配给更新的字符串:

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

此外,您可以在以下代码中使用,而不是在代码中循环文本:

for l in string.punctuation:
     if l in text:
        text = text.replace(l,'')

有几个问题:

  • 字符串是不可变的。这意味着像lower()replace()这样的函数返回结果并保持原始字符串不变。您需要将返回值赋给某个地方。

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

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

相关问题 更多 >