简体   繁体   English

Python:使用正则表达式或逻辑从列表中删除一些字符串内容

[英]Python : Remove few string content from list using regex or logically

I have directory of text files, each line of the file is read as list element and stored in a list我有文本文件目录,文件的每一行都被读取为列表元素并存储在列表中

list = ['abc','[','apple','banana','cucumber',']','efg','{','egg','[fff]','ginger }','end;','abc1','[','apple1','banana1','cucumber1',']','efg1','{','egg1','[fff1]','ginger1 }','end1;']

Now I want to only remove the content inside the stand alone square brackets from the files - looks like'[','apple','banana','cucumber',']' in my list ..rest to be kept untouched.. even the square bracket content inside curly brackets needs to be retained- looks like [fff] content in my list.现在我只想从文件中删除独立方括号内的内容 - 在我的列表中看起来像'[','apple','banana','cucumber',']' ..rest 保持不变。 . 即使是大括号内的方括号内容也需要保留 - 看起来像我列表中的 [fff] 内容。

So i joined all the strings to apply regex operation -所以我加入了所有的字符串来应用正则表达式操作 -

newlist = newlist = [' '.join(list)]
print(newlist)

newlist looks like -新名单看起来像 -

['abc [ apple banana cucumber ] efg { egg [fff] ginger } end; abc1 [ apple1 banana1 cucumber1 ] efg1 { egg1 [fff1] ginger1 } end1;']

Expected output using regex -使用正则表达式的预期输出 -

['abc  efg { egg [fff] ginger } end; abc1  efg1 { egg1 [fff1] ginger1 } end1;']

Pls pls help..请帮助..

This regex will remove the unwanted data per your requirements此正则表达式将根据您的要求删除不需要的数据

import re

list = ['abc','[','apple','banana','cucumber',']','efg','{','egg','[fff]','ginger }','end;','abc1','[','apple1','banana1','cucumber1',']','efg1','{','egg1','[fff1]','ginger1 }','end1;']
newlist = newlist = [' '.join(list)]
newlist = [re.sub('\[ .+? \]', '', newlist[0])]

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

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