繁体   English   中英

python从文件中删除特定行

[英]python remove specific lines from file

我想删除此HTML文件中的特定行。 我想查看字符串STARTDELETE在哪里,并从那里+1删除到字符串ENDDELETE -1

为了更好的理解,我用“ xxx”标记了要删除的行。 我该如何用python做到这一点?

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <div class="container">
    <h2>Image Gallery</h2>
    <div class="row"> <!--STARTDELETE-->
      xxx<div class="col-xs-3">
        xxx<div class="thumbnail">
          xxx<a href="/w3images/lights.jpg" target="_blank">
          xxx<img  style="padding: 20px" src="xxx" alt="bla" >
          xxx<div class="caption">
            xxx<p>Test</p>
          xxx</div>
        xxx</a>
        xxx</div>
      xxx</div>
    </div> <!--ENDDELETE-->
  </div>
</body>
</html>

您可以首先将该代码复制并粘贴到输入文件中,该文件可能名为“ input.txt”,然后将要保留的行输出到“ output.txt”。 忽略要删除的行。

w = open("output.txt", "w")  # your output goes here
delete = False
with open("input.txt") as file:
    for line in file:
        if "<!--ENDDELETE-->" in line:
            delete = False # stops the deleting
        if not delete:
            w.write(str(line))
        if "<!--STARTDELETE-->" in line:
            delete = True # starts the deleting
w.close() # close the output file

希望这可以帮助!

安装beautifulsoup4 (HTML解析器/ DOM操作器)

读取数据,获取一个带有beautifulsoup的“ DOM”(一种可步行的结构),获取您想清空的项目,并删除其子项

在您的示例中,您似乎想清空class=row <div>(s) ,对吗? 假设您的HTML数据存储在名为data.html的文件中(在您的特定情况下,可能不会像这样...它将是请求的正文或类似内容)

from bs4 import BeautifulSoup
with open('data.html', 'r') as page_f:
    soup = BeautifulSoup(page_f.read(), "html.parser")
    # In `soup` we have our "DOM tree"

divs_to_empty = soup.find("div", {'class': 'row'})
for child in divs_to_empty.findChildren():
    child.decompose()

print(soup.prettify())

输出:

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>
   Bootstrap Example
  </title>
  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1" name="viewport"/>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
  </script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
  </script>
 </head>
 <body>
  <div class="container">
   <h2>
    Image Gallery
   </h2>
   <div class="row">
    <!--STARTDELETE-->
   </div>
   <!--ENDDELETE-->
  </div>
 </body>
</html>

如果您要进行DOM操作,我强烈建议您阅读并玩点漂亮的汤(功能很强大)

暂无
暂无

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

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