如何从字符串中提取单个单词并忽略括号和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
相关产品推荐
相关产品推荐

