【问题标题】:defining function that checks strings [closed]定义检查字符串的函数[关闭]
【发布时间】:2020-06-22 11:10:39
【问题描述】:

我最近开始学习 python,我正在尝试定义一个名为 count_text 的函数,但是我很挣扎。

我的目标是创建一个函数来确定在文本中找到多少个字母(小写或大写)、数字、空格或其他字符(即#@^)。该函数应该返回字典中的四个总数,键为"letters""numbers""spaces""others"

例如count_text('Hello123') 应该返回:

{'letters': 3, 'numbers': 3, 'spaces': 0, 'others': 0}

任何帮助将不胜感激。

【问题讨论】:

  • 到目前为止你有没有尝试过?
  • "我正在尝试定义一个名为 "count_text" 的函数,但是我很努力。"好的,你有没有写任何代码?你不明白怎么做的部分是什么?当你说你在“挣扎”时,你在挣扎什么?例如,你知道如何创建任何函数吗?你知道如何检查一个字符是否是字母/数字/等吗?你知道如何创建字典吗?你知道如何使用字典吗?

标签: python function dictionary


【解决方案1】:

您可以将re.findall()len() 一起使用:

import re

t = "Hello123"

def count_text(t):

    d = {'letters': len(re.findall('[a-zA-Z]',t)),
         'numbers': len(re.findall('[0-9]',t)),
         'spaces': len(re.findall(' ',t)),
         'others': len(re.findall('[^a-zA-z0-9]',t))}

    return d

print(count_text("Hello123"))

输出:

{'letters': 5, 'numbers': 3, 'spaces': 0, 'others': 0}

【讨论】:

    【解决方案2】:

    您可以使用正则表达式subn。这里的优点是它将匹配的字符替换为空,然后您将new_string 输入到下一步。也许效率更高一点,一点点? :D

    def count_text(input):
        import re
        result = {}
    
        (new_string, result["letters"]) = re.subn(r'[A-Za-z]','',input)
        (new_string, result["numbers"]) = re.subn(r'\d','',new_string)
        (new_string, result["spaces"]) = re.subn(r'\s','',new_string)
        result["others"] = len(new_string)
    
        return result
    

    测试:

    print(count_text("Hello123"))
    {'letters': 5, 'numbers': 3, 'spaces': 0, 'others': 0}
    print(count_text("Hello 1 2 3"))
    {'letters': 5, 'numbers': 3, 'spaces': 3, 'others': 0}
    print(count_text("Hello $1 &2 *3!"))
    {'letters': 5, 'numbers': 3, 'spaces': 3, 'others': 4}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      相关资源
      最近更新 更多