检查行是否与文件中的另一行相同

时间:2020-06-25 23:08:25

标签: python

我要检入文件,它将检查所有行,如果一行与其他任何行相同;代码将说“行号B与行号A相同”。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sign up </title>
</head>
<body>
  <div class="Header">
      <a href="/" class="LogoWrapper" >
      <img src="D:\my-angular-projects\signup-form\src\image\Snap.jpg" alt="Scone O'Clock logo" />
      </a>
      <p class="Strap">Scones: the most resplendent of snacks </p>
   </div>

        <div class="IntroWrapper">
            <p class="IntroText">
              Occasionally maligned and misunderstood; the scone is a quintessentially British classic.
            </p>
         <div class="MoneyShot">
              <img class="MoneyShotImg" src="D:\my-angular-projects\signup-form\src\image\1555932407.jpg" alt="Incredible scones" />
              <p class="ImageCaption">Incredible scones, picture from Wikipedia</p>
         </div>
       </div>
     <p>Recipe and serving suggestions follow.</p>
   <div class="Ingredients">
      <h3 class="SubHeader">
      Ingredients</h3>
      <ul>
     </ul>
    </div>
   <div class="HowToMake">
    <h3 class="SubHeader">Method</h3>
    <ol class="MethodWrapper">
    </ol>
   </div>
</body>

   

 </html>
  • 如果可能但不重要,请使其更快。
  • 如果可能的话,我们是否可以每5行检查一次,就像它只会检查第5、10、15、20 ...行?
  • 行号在实际文件中不存在。它们仅用于显示行号。

1 个答案:

答案 0 :(得分:0)

就像这样,它应该可以工作:

with open('lines.txt','r') as f:
    lines = f.read().splitlines()

for i1,l1 in enumerate(lines):
    for i2,l2 in enumerate(lines[i1+1:]):
        
        if l1 == l2:
            print(f"Alert: Line {i1+1} is the same with line {i1+i2+2}!")