使用python从文件中过滤和删除特定的多行文本

2024-04-20 05:41:25 发布

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

我正在编写一个python工具来处理一组文件。这个工具将被其他用户使用,而不是我。在

文件类似于以下格式:

#Text which I want to keep intact
#Lots of text 
#Lots and lots of text 
#Lots and lots and lots of other text 

#Then in-between the file I have text in this format which I want to operate on:

ginstance 
{ 
 name ginstance_053D627B1349FA0BC57 
 node "FINDME" 
 inherit_xform on 
 visibility 255 
blah 
blah 
blah 
} 

ginstance 
{ 
 name ginstance_053D627B1349FA0BC57 
 node "DONTFINDME" 
 inherit_xform on 
 visibility 255 
blah 
blah 
blah 
} 

我想做的是:

  1. 在输入文件中查找这些实例。在
  2. 检查实例中的特定单词。E、 g“查找”
  3. 如果上述单词存在,则从文件中删除该实例。 i、 删除从“ginstance”到波形括号“}”的文本

我的工具将从使用UI的用户那里获取此搜索项(“FINDME”)。在

我可以找到要删除的实例:

^{pr2}$

此外,此代码从输入文件中删除所有实例并将结果写入输出:

^{3}$

但我不想删除所有实例,只删除其中包含“FINDME”的实例。 如何编写一个包含这两个因素的python代码呢。在

希望我能清楚地回答这个问题。非常感谢。在

我搜索了很多关于堆栈溢出的问题,并且在发布这个问题之前尝试了很多答案。在


Tags: and文件工具of实例text用户which
3条回答

试试这个

ginstance.*?{.*?node\s*"FINDME".*?}

Regex Demo

输入

^{pr2}$

输出

MATCH 1
1.  [194-317]   `
ginstance 
{ 
 name ginstance_053D627B1349FA0BC57 
 node "FINDME" 
 inherit_xform on 
 visibility 255 
blah 
blah 
blah 
}`

你不认为FINDME也存在于DONTFINDME中吗?这就是为什么它是匹配的两个。如果它在quotes,那么使用这个

if "\"FINDME\"" in a: 
    print a

或者更好的方法是使用re.search()。它包含单词边界(\b

^{pr2}$

你可以采用这种方法:

ginstance\s*\{     # look for ginstance { literally
[^}]*              # anything not a }
(?:node\ "FINDME") # node "FINDME" literally
[^}]*              # anything not a }
\}                 # the closing }

它假定,ginstance的内部块中没有其他}
Python中,这将是:

^{pr2}$

请参见a demo on regex101.com以及on ideone.com。在

相反:


考虑到你的意见(为了达到相反的效果),你可以采用消极的前瞻性解决方案,如下所示:

ginstance\s*\{
(?:
    [^}]
    (?!(?:node\ "FINDME"))
)+
\}

也可以参见这个one on regex101.com的演示。在

相关问题 更多 >