You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中按Cluster提取以逗号分隔的分组数字

提取Cluster数字集合的Python实现

我来帮你搞定这个问题!从你给出的集群文本里提取每个Cluster对应的数字集合,用Python可以通过正则表达式轻松实现,这种方法能精准匹配文本里的Cluster结构,处理起来很可靠。

实现步骤和代码示例

首先,我们把你的原始文本作为输入字符串,然后用正则匹配每个Cluster的编号和对应的数字列表,最后把数字字符串转换成整数列表存储起来:

import re

# 你的原始集群文本
input_text = """Cluster 7: {4, 15, 21, 28, 33, 35, 43, 47, 53, 57, 59, 66, 69, 70, 74, 86, 87, 88, 90, 114, 136, 148, 201, 202, 212, 220, 227, 250, 252, 253, 259, 262, 267, 270, 282, 296, 318, 319, 323, 326, 341} Cluster 8: {9, 10, 11, 20, 39, 55, 79, 101, 108, 143, 149, 221, 279, 284, 285, 286, 287, 327, 333, 334, 335, 336} Cluster 9: {3, 64, 83, 93, 150, 153, 264, 269, 320, 321, 322} Cluster 10: {94, 123, 147}"""

# 定义正则模式:匹配Cluster编号和括号内的数字字符串
pattern = r'Cluster (\d+): \{([\d, ]+)\}'
# 找出所有匹配的Cluster条目
matches = re.findall(pattern, input_text)

# 把结果整理成字典:键是Cluster编号(整数),值是数字列表(整数)
clusters = {}
for cluster_num_str, nums_str in matches:
    # 分割数字字符串,去掉多余空格,转换为整数
    number_list = [int(num.strip()) for num in nums_str.split(',') if num.strip()]
    clusters[int(cluster_num_str)] = number_list

# 验证结果
for cluster_id, numbers in clusters.items():
    print(f"Cluster {cluster_id}: {numbers}")

代码说明

  • 正则模式:r'Cluster (\d+): \{([\d, ]+)\}' 用来匹配每个Cluster的结构:
    • (\d+) 捕获Cluster的编号(比如7、8);
    • \{([\d, ]+)\} 捕获大括号内的所有数字和分隔符;
  • 数字处理:用split(',')分割数字字符串,再通过strip()去掉每个数字前后的空格,最后转成整数,同时过滤掉可能的空字符串(避免因空格导致的无效元素);
  • 存储结构:用字典存储结果,方便你通过Cluster编号快速获取对应的数字列表,比如clusters[7]就能得到Cluster 7的所有数字。

内容的提问来源于stack exchange,提问作者Rafael Rios

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:14:17