700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python读取txt每一行按照正则匹配hon-正则表达式使用python从文件中过滤和删除特定的

python读取txt每一行按照正则匹配hon-正则表达式使用python从文件中过滤和删除特定的

时间:2022-04-20 09:09:24

相关推荐

python读取txt每一行按照正则匹配hon-正则表达式使用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

}

我想做的是:

>在输入文件中找到这些实例.

>检查实例中的特定单词.例如“ FINDME”

>如果以上单词存在,则从文件中删除实例.

即删除从“实例”开始到波浪形括号“}”的文本

我的工具将使用用户界面从用户那里获取此搜索字词(“ FINDME”).

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

import re

with open("path to input file", "r") as input:

with open("path to output file", "w") as output:

xfile = input.read()

instance = re.findall(r"ginstance.*?}", xfile, re.DOTALL)

for a in instance:

if "FINDME" in a:

print a

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

data = re.sub("ginstance.*?}", "", xfile, flags=re.DOTALL)

output.write(data)

但是我不想删除所有实例,只删除其中带有“ FINDME”的实例.

如何编写包含这两个因素的python代码.

希望我清楚这个问题.谢谢.

我已经在堆栈溢出问题上进行了大量搜索,并在发布此问题之前尝试了很多答案.

python读取txt每一行按照正则匹配hon-正则表达式使用python从文件中过滤和删除特定的多行文本...

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。