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

如何在Python字符串中提取指定关键词对应的数值(如word1的1434)

提取word1对应数值的解决方法

方法一:正则表达式(推荐)

直接通过正则匹配关键词后的数值,一步到位:

import re

text = 'word1:1434, word2:4446, word3:7171'
keyword = 'word1'

# 匹配关键词+冒号+连续数字,括号捕获数值部分
match_result = re.search(f'{keyword}:(\d+)', text)
if match_result:
    target_value = match_result.group(1)
    print(target_value)  # 输出 1434

原理:\d+匹配一个或多个数字,括号将数值部分标记为捕获组,通过group(1)就能提取出目标数值。

方法二:基于你现有代码的优化

如果你想继续用partition的思路,只需对得到的after_keyword做进一步处理:

text = 'word1:1434, word2:4446, word3:7171'
keyword = 'word1'

before_keyword, keyword, after_keyword = text.partition(keyword)
# 去掉开头的冒号,再按逗号分割取第一部分
target_value = after_keyword.lstrip(':').split(',')[0].strip()
print(target_value)  # 输出 1434

原理:lstrip(':')移除开头的冒号,split(',')将字符串按逗号拆分为列表,取第一个元素就是目标数值,strip()用于处理可能存在的空格(增强鲁棒性)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:01:02