首页 > 解决方案 > 程序不会停止遍历列表

问题描述

def gameinfo():
    lines = []
    html_doc = 'STATIC.html'
    soup = BeautifulSoup(open(html_doc), 'html.parser')
    for mytable in soup.find_all('table'):
        for trs in mytable.find_all('tr'):
            tds = trs.find_all('td')
            row1 = [elem.text.strip() for elem in tds]
            row = str(row1)

            sausage = False
            with open("FIRE.txt", "r+") as file:
                for line in file:
                    if row+"\n" in line:
                        break

                else:
                     if row.split(",")[:4] == line.split(",")[:4]:
                        print(row)
                        print(line)
                        file.write(line.replace(line+"\n", row+"\n"))
                        print('Already exists with diff date')
                        sausage = True
                        break

                if sausage == False:
                    print(row.split(",")[:4])
                    print(line.split(",")[:4])
                    print(row)
                    print(line)
                    file.write(row+"\n") 
                    print('appended')

    while True:
        gameinfo()

gameinfo()

该程序应该继续在文本文件中搜索FIRE.txt与变量匹配的行row。当我运行它时,它工作正常,但是应该检查列表的前四个元素是否相同的代码部分,然后皮肤下面的附加部分,不起作用。当程序检测到字符串的前 4 个元素变成了与文本文件中另一个字符串的前 4 个元素匹配的列表(行)时,它应该覆盖文本文件中的字符串。但是,当它检测到具有相同前 4 个元素的列表时,它会永远循环并且永远不会中断。

我的字符串如下所示: ['Infield Upper Deck Reserved 529', '$17.29', '4', '2', '175'] 我将其与如下列表进行比较: ['Infield Upper Deck Reserved 529 ', '$17.29', '4', '2', '170'] 并且当它看到列表中的前 4 个元素相同时,它应该覆盖文本文件中开始的那个,但是它正在循环。

标签: python-3.x

解决方案


问题变了;最新版本最后。


我认为您想使用该csv模块。如果您直接遍历一个csv.reader对象而不是文件对象,您将获得每一行作为一个列表。

例子:

import csv

row = ["this", "is", "an", "example"]
with open("FIRE.txt", "r+") as file:
    reader = csv.reader(file)
    for line in reader:
        if row in line:
            break
        pass

或者,如果您不需要在 Python 以外的任何东西中使用它,您可以pickle使用collections.OrderedDict前四个项目的元组作为键:

import collections
import pickle
import contextlib

@contextlib.contextmanager
def mutable_pickle(path, default=object):
    try:
        with open(path, "rb") as f:
            obj = pickle.load(f)
    except IOError, EOFError:
        obj = default()

    try:
        yield obj
    finally:
        with open(path, "wb") as f:
            pickle.dump(obj, f)

with mutable_pickle("fire.bin",
                    default=collections.OrderedDict) as d:
    for row in rows:
        d[tuple(row[:4])] = row

推荐阅读