从字符串中删除大括号内(可能嵌套)的所有文本

2024-06-06 17:14:15 发布

您现在位置:Python中文网/ 问答频道 /正文

对于NLP项目,我希望对文本进行预处理,这些文本有时会在类似JSON的大括号中包含不需要的内容,例如:

Some useful content here {"contentId":"QI9GPST0AFB401","dimensions":{"large_desktop":[[120,60]]}} good stuff here {some other curly braces}

我所要做的就是删除大括号内的文本,并将其保留

Some useful content here good stuff here

复杂性似乎来自这样一个事实,即存在多组大括号,这会取消像this one这样的解决方案的资格,并且存在嵌套的大括号,这会取消像this one这样基于正则表达式的解决方案的资格


Tags: 项目文本jsonherenlpsomecontent大括号
3条回答

目前我无法尝试,但只要支架始终保持完全平衡,这应该会起作用

import re
def removeBracedContent(s):
    while ‘{‘ in s:
        if ‘}’ not in s:
            raise Exception( “The braces weren’t balanced - too many {” )
        s = re.sub(‘{[^{}]*}’,’’,s)
    if ‘}’ in s:
        raise Exception( “The braces weren’t balanced - too many }” )
    return s

这会重复删除最里面的匹配大括号,包括它们之间的任何文本,直到没有任何文本为止

如果大括号中的内容分布在多行上,则必须向re.sub-flags=re.DOTALL添加最后一个参数

在99%的情况下,regex将完成这项工作

import re

s = 'Some useful content here {"contentId":"QI9GPST0AFB401","dimensions":{"large_desktop":[[120,60]]}} good stuff here {some other curly braces}'

ss = re.sub(r'{[^}]*}*', '', s)

print(ss)

输出

Some useful content here  good stuff here 

这听起来是一个不错的求职面试问题:)

我只需要手动解析字符串:

def cleanString(dirty):
    clean = ""
    bad = 0

    for c in dirty:
        if c == '{':
            bad += 1
        elif c == '}':
            bad -= 1
        elif bad == 0:
            clean +=c

    return clean

相关问题 更多 >