程序不会停止遍历列表

时间:2018-08-21 06:10:43

标签: python-3.x

new_sentence = sentence
for brand, generic in BRANDS.items():
    new_sentence = new_sentence.replace(brand, generic)
print(new_sentence)

该程序应该继续在文本文件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相匹配的行。当我运行它时,它可以正常工作,但是应该检查列表中前四个元素是否相同,然后将下面的附加部分换肤的代码部分不起作用。当程序检测到字符串的前4个元素变为与文本文件中另一个字符串的前4个元素匹配的列表(行)时,它应覆盖文本文件中的字符串。但是,当它检测到具有相同的前4个元素的列表时,它将永远循环并永远不会中断。

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

1 个答案:

答案 0 :(得分:0)

问题已经改变;最新版本。


您想使用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之外的其他任何方式上使用它,则可以picklecollections.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