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

如何从字符串中提取单个单词并忽略括号和Python关键字

问题解决思路

你现有代码的问题是直接按空格拆分字符串,括号会和相邻单词绑定(比如示例中的(Columbia、(India),无法单独剥离括号。
推荐直接用正则匹配所有纯字母组成的连续串,再过滤Python关键字即可,实现代码如下:

import keyword
import re

my_str = input()
# 匹配所有连续的大小写字母串,自动忽略括号、空格等非字母内容
all_letter_strs = re.findall(r'[a-zA-Z]+', my_str)
# 过滤掉Python关键字
res = [item for item in all_letter_strs if not keyword.iskeyword(item.lower())]
print(res)

测试效果

输入示例内容:(Columbia and (India or Singapore) and Malaysia)
输出结果:['Columbia', 'India', 'Singapore', 'Malaysia'],完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:39:02