MST

星途 面试题库

面试题:Python正则闭包操作符的复杂应用

假设有一个字符串列表,其中每个字符串可能包含形如'word1{3,5}word2'这样由闭包操作符修饰的子串,要求编写一个Python函数,该函数接收这个字符串列表,返回每个字符串中符合上述格式的子串,并统计每个子串中闭包操作符所指定的频数范围(即3到5这样的范围)出现的次数,详细说明你的实现思路和代码逻辑。
19.2万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 利用正则表达式识别字符串中形如 'word1{3,5}word2' 的子串。
  2. 从识别出的子串中提取闭包操作符指定的频数范围,并统计每个范围出现的次数。

代码逻辑

  1. 导入 re 模块用于正则表达式操作。
  2. 定义函数,接收字符串列表作为参数。
  3. 使用正则表达式匹配符合格式的子串。
  4. 遍历匹配到的子串,提取频数范围并更新统计字典。
  5. 返回包含子串及其频数范围统计的结果。

代码示例

import re


def count_substring_ranges(str_list):
    result = {}
    pattern = re.compile(r'(\w+\{\d+,\d+\}\w+)')
    for string in str_list:
        matches = pattern.findall(string)
        for match in matches:
            range_str = re.search(r'\{(\d+,\d+)\}', match).group(1)
            if match not in result:
                result[match] = {range_str: 1}
            else:
                if range_str in result[match]:
                    result[match][range_str] += 1
                else:
                    result[match][range_str] = 1
    return result


你可以使用以下方式调用这个函数:

str_list = ["test{2,4}example", "test{2,4}example", "other{1,3}word"]
print(count_substring_ranges(str_list))