为了账号安全,请及时绑定邮箱和手机立即绑定

查找 i 出现最多的特殊字符

查找 i 出现最多的特殊字符

喵喵时光机 2021-08-02 16:04:39
我有一个任务,我需要计算字符串中出现最多的特殊字符。我拥有的文件包含三个带有文本的段落,我需要将它们相互比较以查看一组字符出现的位置,然后计算它们出现最多的位置。文本中的行: 'I cannot go now. Give me lunch first at 12:15.'After 13:100, he took a nap for until 13:15. Then in the late afternoon on 2018-11:30 at 16:30, he picked some bags and went to the palace. On the way, he felt hot so he sat under a tree to rest. Then, two hours later at 18:30, he got up to go but saw a man showing some magic tricks. He stopped to watch for an until 21:04.When he reached the palace it was already after 21:03. The palace gates had been shut. So Haria had lost a golden chance because he had not learned the value of time on the 2018-13-01, a beautiful day.我到目前为止的代码:number_of_specials = 0c = ['.', '.', ';', ':', '!', '?']top = []top_c1 = 0top_c2 = 0top_c3 = 0with open(TEXT, "r") as fh:    for line in fh:        top.append(line.split("\n")) //to get the linesif c in top[0]:    top_c1 += 1不知道从哪里开始,任何指针将不胜感激
查看完整描述

2 回答

?
炎炎设计

TA贡献1808条经验 获得超4个赞

试试这个:


import re

c = ['.', '.', ';', ':', '!', '?']

top = ['asdd..,;;.:']

top_len = len(re.findall('['+''.join(c)+']',top[0]))


查看完整回答
反对 回复 2021-08-03
?
HUWWW

TA贡献1874条经验 获得超12个赞

您可以在元组中存储行和出现次数,并按字符串(行)中特定字符的数量增加出现次数值。


class Counter(object): # mutable object is needed to access it from tuple

    def __init__(self, start_value=0):

        self.value = start_value


    def __str__(self):

        return str(self.value)


c = ['.', '.', ';', ':', '!', '?']

top = []


with open(TEXT, "r") as fh:

    for line in fh:

        top.append((line.split("\n"), Counter(0)))


for line, occurrences in top:

    for character in c:

        occurrences.value += line.count(character)


查看完整回答
反对 回复 2021-08-03
  • 2 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号