使用Python提取嵌套括号中的句子

2024-09-28 22:24:21 发布

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

我在一个目录中有多个.txt文件。 以下是我的.txt文件的一个示例:

kkkkk;

  select xx("xE'", PUT(xx.xxxx.),"'") jdfjhf:jhfjj from xxxx_x_xx_L ;
quit; 

/* 1.xxxxx FROM xxxx_x_Ex_x */ 
proc sql; ("TRUuuuth");
hhhjhfjs as fdsjfsj:
select * from djfkjd to jfkjs
(
SELECT abc AS abc1, abc_2_ AS efg, abc_fg, fkdkfj_vv, jjsflkl_ff, fjkdsf_jfkj
    FROM &xxx..xxx_xxx_xxE
where ((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.) and 
      (xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.))
 );


jjjjjj;

  select xx("xE'", PUT(xx.xxxx.),"'") jdfjhf:jhfjj from xxxx_x_xx_L ;
quit; 

/* 1.xxxxx FROM xxxx_x_Ex_x */ ()
proc sql; ("CUuuiiiiuth");
hhhjhfjs as fdsjfsj:
select * from djfkjd to jfkjs
(SELECT abc AS abc1, abc_2_ AS efg, abc_fg, fkdkfj_vv, jjsflkl_ff, fjkdsf_jfkj
    FROM &xxx..xxx_xxx_xxE
where ((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.) and 
      (xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.))(( ))
 );

我试图在我的.txt文件中提取嵌套括号中的所有句子。你知道吗

我尝试了多种方法,比如stacking圆括号,但是当代码通过一个.txt文件进行解析时,出现了一个错误,即“列表索引超出范围”。我猜是因为括号里没有写什么。你知道吗

我也用regex尝试过,使用以下代码:

with open('lan sample text file.txt','r') as fd:
    lines = fd.read()

    check = set()
    check.add("Select")
    check.add("select")
    check.add("SELECT")
    check.add("from")
    check.add("FROM")
    check.add("From")
    items=re.findall("(\(.*)\)",lines,re.MULTILINE)
    for x in items:
        print(x)

但我的结论是:

("xE'", PUT(xx.xxxx.),"'"
("TRUuuuth"
((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.
(xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.)
("xE'", PUT(xx.xxxx.),"'"
("CUuuiiiiuth"
((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.
(xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.)

我想要的输出应该是这样的:

("xE'", PUT(xx.xxxx.),"'")
("TRUuuuth")
(
SELECT abc AS abc1, abc_2_ AS efg, abc_fg, fkdkfj_vv, jjsflkl_ff, fjkdsf_jfkj
    FROM &xxx..xxx_xxx_xxE
where ((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.) and 
      (xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.))
 )
("xE'", PUT(xx.xxxx.),"'")
("CUuuiiiiuth")
(SELECT abc AS abc1, abc_2_ AS efg, abc_fg, fkdkfj_vv, jjsflkl_ff, fjkdsf_jfkj
    FROM &xxx..xxx_xxx_xxE
where ((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.) and 
      (xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.))(( ))
 )

Tags: fromformatputcheckasxxxixgff
2条回答

我想说我的解决方案不是最优化的,但它能解决你的问题。你知道吗

解决方案(只需更换测试.txt使用您的文件名)

result = []
with open('test.txt','r') as fd:
    # To keep track of '(' and ')' parentheses
    parentheses_stack = []
    # To keep track of complete word wrapped by ()
    complete_word = []
    # Iterate through each line in file
    for words in fd.readlines():
        # Iterate each character in a line
        for char in list(words):
            # Initialise the parentheses_stack when you find the first open '(' 
            if char == '(':
                parentheses_stack.append(char)
            # Pop one open '(' from parentheses_stack when you find a ')'
            if char == ')':
                if not parentheses_stack = []:
                    parentheses_stack.pop()
                if parentheses_stack == []:
                    complete_word.append(char)
            # Collect characters in between the first '(' and last ')'
            if not parentheses_stack == []:
                complete_word.append(char)
            else:
                if not complete_word == []:
                    # Push the complete_word once you poped all '(' from parentheses_stack
                    result.append(''.join(complete_word))
                    complete_word = []



for res in result:
    print(res)

结果:

WS:python rameshrv$ python3 /Users/rameshrv/Documents/python/test.py
("xE'", PUT(xx.xxxx.),"'")
("TRUuuuth")
(
SELECT abc AS abc1, abc_2_ AS efg, abc_fg, fkdkfj_vv, jjsflkl_ff, fjkdsf_jfkj
    FROM &xxx..xxx_xxx_xxE
where ((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.) and 
      (xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.))
 )
("xE'", PUT(xx.xxxx.),"'")
()
("CUuuiiiiuth")
(SELECT abc AS abc1, abc_2_ AS efg, abc_fg, fkdkfj_vv, jjsflkl_ff, fjkdsf_jfkj
    FROM &xxx..xxx_xxx_xxE
where ((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.) and 
      (xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.))(( ))
 )

如我所说,这是Python: How to match nested parentheses with regex?的一个副本,它显示了几种处理嵌套括号的方法,而不是所有的方法都是基于regex的。一种方法确实需要PYPI存储库中的regex模块。如果text包含该文件的内容,则应执行以下操作:

import regex as re

text = """kkkkk;

  select xx("xE'", PUT(xx.xxxx.),"'") jdfjhf:jhfjj from xxxx_x_xx_L ;
quit;

/* 1.xxxxx FROM xxxx_x_Ex_x */
proc sql; ("TRUuuuth");
hhhjhfjs as fdsjfsj:
select * from djfkjd to jfkjs
(
SELECT abc AS abc1, abc_2_ AS efg, abc_fg, fkdkfj_vv, jjsflkl_ff, fjkdsf_jfkj
    FROM &xxx..xxx_xxx_xxE
where ((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.) and
      (xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.))
 );


jjjjjj;

  select xx("xE'", PUT(xx.xxxx.),"'") jdfjhf:jhfjj from xxxx_x_xx_L ;
quit;

/* 1.xxxxx FROM xxxx_x_Ex_x */ ()
proc sql; ("CUuuiiiiuth");
hhhjhfjs as fdsjfsj:
select * from djfkjd to jfkjs
(SELECT abc AS abc1, abc_2_ AS efg, abc_fg, fkdkfj_vv, jjsflkl_ff, fjkdsf_jfkj
    FROM &xxx..xxx_xxx_xxE
where ((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.) and
      (xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.))(( ))
 );"""    

regex = re.compile(r"""
(?<rec> #capturing group rec
 \( #open parenthesis
 (?: #non-capturing group
    [^()]++ #anything but parenthesis one or more times without backtracking
  | #or
    (?&rec) #recursive substitute of group rec
 )*
 \) #close parenthesis
)
""", flags=re.VERBOSE)

for m in regex.finditer(text):
    groups = m.captures('rec')
    group = groups[-1] # the last group is the outermost nesting
    if re.match(r'^\(+\s*\)+$', group):
        continue # not interested in empty parentheses such as '( )'
    print(group)

印刷品:

("xE'", PUT(xx.xxxx.),"'")
("TRUuuuth")
(
SELECT abc AS abc1, abc_2_ AS efg, abc_fg, fkdkfj_vv, jjsflkl_ff, fjkdsf_jfkj
    FROM &xxx..xxx_xxx_xxE
where ((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.) and
      (xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.))
 )
("xE'", PUT(xx.xxxx.),"'")
("CUuuiiiiuth")
(SELECT abc AS abc1, abc_2_ AS efg, abc_fg, fkdkfj_vv, jjsflkl_ff, fjkdsf_jfkj
    FROM &xxx..xxx_xxx_xxE
where ((xxx(xx_ix as format 'xxxx-xx') gff &jfjfsj_jfjfj.) and
      (xxx(xx_ix as format 'xxxx-xx') lec &jgjsd_vnv.))(( ))
 )

相关问题 更多 >