【问题标题】:Why is it still printing为什么还在打印
【发布时间】:2015-02-17 01:08:13
【问题描述】:

我有 2 个 txt 文件,一个有多余的行。我只想提取多余的行。它不断打印所有内容。为什么?我是说如果 txt1 的第一行不等于 txt 2 的第一行,那么打印它。

import os, sys

htmlRub = ""

path = "./filter.txt"
if os.path.isfile(path):
    oFile = open(path)
    filter = oFile.read()
    oFile.close()
else:
    print("Filter file is missing")

path = "./database.txt" #The HTML code downloaded
if os.path.isfile(path):
    oFile = open(path)
    htmlRub = oFile.read() #The HTML code downloaded
    oFile.close()
else:
    print("Database file is missing")

filterData = filter.split("\n")
htmlData = htmlRub.split("\n") #The HTML code downloaded


for line in htmlData:
    for lineagain in filterData:
        if line != lineagain:
            print(line)
            break
        else:
            pass
            break

【问题讨论】:

  • 你打算在双 for 循环末尾的 passbreak 语句做什么?
  • 在最后一个循环中,内部的lopp 只会执行一次。您在 ifelse 语句中都有中断。

标签: python string for-loop split extract


【解决方案1】:

如果我理解正确,您正试图从 htmlData 中删除 filterData 中的所有字符串。我希望。

delta = [s for s in htmlData if s not in filterData]
for s in delta:
    print s

正如 cmets 所说,您的循环没有按照您的想法进行。 列表理解的一种循环格式是:

for hline in htmlData:
    if hline not in filterData:
        print hline

【讨论】:

    【解决方案2】:

    克里斯托弗,

    为了使您的代码基本保持不变,您似乎只需要更改:

    if line != lineagain:
        print(line)
    else:
        pass
        break
    

    到:

    if line != lineagain:
        print(line)
    else:
        continue
    

    robert_x44 的回答更像是“Pythonic”。

    【讨论】:

    • 谢谢,但我的代码失败了,无论我在 48 小时内写了什么,它都会打印所有内容。我的代码失败了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2014-03-23
    • 2020-01-11
    • 2020-01-10
    相关资源
    最近更新 更多