python删除txt指定内容_正则表达式使用python从文件中过滤和删除特定的多行文本...
我正在編寫一個(gè)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
}
我想做的是:
>在輸入文件中找到這些實(shí)例.
>檢查實(shí)例中的特定單詞.例如“ FINDME”
>如果以上單詞存在,則從文件中刪除實(shí)例.
即刪除從“實(shí)例”開始到波浪形括號(hào)“}”的文本
我的工具將使用用戶界面從用戶那里獲取此搜索字詞(“ FINDME”).
我可以找到要?jiǎng)h除的實(shí)例:
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
此外,此代碼從輸入文件中刪除所有實(shí)例,并將結(jié)果寫入輸出:
data = re.sub("ginstance.*?}", "", xfile, flags=re.DOTALL)
output.write(data)
但是我不想刪除所有實(shí)例,只刪除其中帶有“ FINDME”的實(shí)例.
如何編寫包含這兩個(gè)因素的python代碼.
希望我清楚這個(gè)問題.謝謝.
我已經(jīng)在堆棧溢出問題上進(jìn)行了大量搜索,并在發(fā)布此問題之前嘗試了很多答案.
總結(jié)
以上是生活随笔為你收集整理的python删除txt指定内容_正则表达式使用python从文件中过滤和删除特定的多行文本...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 研究生夏令营计算机题目,2017计算机学
- 下一篇: erp采购总监个人总结_《用友 ERP