简体   繁体   English

如何从括号中删除字符串,包括带有条件的括号?

[英]How to remove a string from brackets including the brackets with a condition?

I have a question similar to this one .我有一个与此类似的问题。

I want to remove brackets and the text within, but keep some words.我想删除括号和其中的文字,但保留一些文字。 For example I have a list:例如我有一个列表:

["Going", "(#)", "(maybe)", "to", "the", "(##)", "(mall)", "market"]

I want to keep (#) and (##) , but remove (maybe) and (mall) .我想保留(#)(##) ,但删除(maybe)(mall)

Expected output:预期输出:

["Going", "(#)", "to", "the", "(##)", "market"]

There can be any number of words with brackets in the list just like 'maybe' and 'mall' .列表中可以有任意数量的带括号的单词,例如'maybe''mall'

Brackets with # can have maximum of 3 hash.#的括号最多可以有 3 个哈希。

You can use a list-comprehension to filter the original list using a regular expression:您可以使用列表理解来使用正则表达式过滤原始列表:

import re

a = ["Going", "(#)", "(maybe)", "to", "the", "(##)", "(mall)", "market"]
b = [word for word in a if re.match(r"[^(]|\(#{1,3}\)", word)]

Gives:给出:

['Going', '(#)', 'to', 'the', '(##)', 'market']

re.match matches the pattern from the beginning of the string. re.match匹配字符串开头的模式。 The pattern means:图案的意思是:

  • [^(] - any character except ( . [^(] -(之外的任何字符。
  • | - or... - 或者...
    • \( - literal parenthesis \( - 文字括号
    • #{1,3} - 1 to 3 repetitions of # #{1,3} - 1 到 3 次重复#
    • \) - literal parenthesis \) - 文字括号

Regex demo正则表达式演示

In a generic way you can parse the list and assess if the word has a pair of brackets.以一种通用的方式,您可以解析列表并评估该单词是否有一对括号。 If it does, and if the word inside is not #, ## or ### , then you should exclude it from the output.如果是这样,并且里面的单词不是#、## 或 ### ,那么您应该将其从输出中排除。 Assuming you have a list of strings:假设您有一个字符串列表:

a = ['Going', '(#)', '(maybe)', 'to', 'the', '(##)', '(mall)', 'market']

output = [word for word in a if ('(' not in word and ')' not in word) or word.strip('()') in ['#', '##', '###']]
print(output)
# ['Going', '(#)', 'to', 'the', '(##)', 'market']

The strip method keeps only the string within the given parameters (in this case ( and ) ). strip方法只保留给定参数中的字符串(在本例中为() )。

You can learn more about list comprehensions here:https://www.w3schools.com/python/python_lists_comprehension.asp您可以在此处了解有关列表推导的更多信息:https ://www.w3schools.com/python/python_lists_comprehension.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM