1
input = (Columbia and (India  or Singapore) and Malaysia)

output = [Columbia, India, Singapore, Malaysia]

基本上忽略python关键字和括号

我尝试使用下面的代码,但仍然无法消除大括号。

import keyword

my_str=input()
l1=list(my_str.split(" "))
l2=[x for x in l1 if not keyword.iskeyword((x.lower()))]
print(l2)
4

2 回答 2

2
import keyword
my_str=input()
my_str = re.sub(r'[\(\)\[\]{}]','',my_str)
l1=list(my_str.split(" "))
l2=[x for x in l1 if not keyword.iskeyword((x.lower()))]
print(l2)

re.sub(r'[\(\)\[\]{}]','',my_str)

这将用空字符串替换各种大括号(从而删除它们)。

于 2021-08-27T17:52:09.250 回答
2

试试这个:

import re
from keyword import iskeyword

inp = '(Columbia and (India or Singapore) and Malaysia)'

c = re.compile(r'\b\w+\b')

print([i.group() for i in c.finditer(inp) if not iskeyword(i.group().lower())])

输出 :

['Columbia', 'India', 'Singapore', 'Malaysia']

没有正则表达式:

from keyword import iskeyword

inp = '(Columbia and (India or Singapore) and Malaysia)'

res = []
for i in inp.split():
    stripped = i.strip('()[]{}')
    if not iskeyword(stripped):
        res.append(stripped)

print(res)
于 2021-08-27T17:57:07.130 回答