我需要解析一个句子:“爱丽丝是个男孩。”分为“爱丽丝”、“男孩”和“大象是哺乳动物”。变成“大象”“哺乳动物”。这意味着我需要将字符串拆分为'is‘,同时删除'a/an’。有什么优雅的方法吗?
发布于 2017-04-30 22:57:48
如果您坚持使用regex,可以使用re.search这样做。
print(re.search('(\w+) is [a|an]? (\w+)',"Alice is a boy.").groups())
# output: ('Alice', 'boy')
print(re.search('(\w+) is [a|an]? (\w+)',"An elephant is a mammal.").groups())
# output: ('elephant', 'mammal')
# apply list() if you want it as a list发布于 2017-04-30 22:09:15
这个答案并不能使我们成为regex,而是一种做事的方式:
s = 'Alice is a boy'
s = s.split() # each word becomes an entry in a list
s = [word for word in s if word != 'a' and word !='an' and word !='is']这样做的主要缺点是,你需要列出你想要排除在列表理解中的每一个单词。
https://stackoverflow.com/questions/43711781
复制相似问题