Python CSV阅读器搜索字符串找到匹配项

时间:2018-08-03 18:55:35

标签: python

再次提出另一个问题。

前言:使用Qt Designer,搜索按钮构建GUI,解析csv数据,并使用找到的数据构建TableWidget。

我有一个文件,该文件具有两个相似的结果,例如,一个位置标记为Reddit(North)和Reddit(South)。如果我搜索Reddit,则仅显示第一个结果,但是当我再次按“搜索”按钮时,它仅显示第一个结果,而不显示第二个结果。

问题:如何在第一场比赛中停止csv阅读器,在表中填入从第一次点击中找到的数据,然后再次点击搜索按钮以清除第一次点击并显示第二个命中?

def search(self):
    self.table_search.setRowCount(6)
    self.table_search.setColumnCount(1)
    self.table_search.verticalHeader().setDefaultSectionSize(20)
    self.table_search.verticalHeader().setVisible(True)
    self.table_search.setVerticalHeaderLabels([
                            'Location ID:', 
                            'Location Name:', 
                            'Cost Center:', 
                            'Street Address:', 
                            'City:', 
                            'State:']
    )

    # taking input from a PyQt line edit box
    search = self.lineedit_locsearch.text()
    search_string = search.strip().upper() # stripping white space from the string

    # containers for specific data from the csv file
    locid = ''
    locname = ''
    loccost = ''
    locaddress = ''
    loccity = ''
    locstate = ''

    with open('data/loc.csv', "r") as locdata:
        reader = csv.reader(locdata)

        for row in reader: 
            for field in row: 
                if field == search_string: 
                    locid = row[0]
                    locname = row[1]
                    loccost = row[2]
                    locaddress = row[3]
                    loccity = row[4]
                    locstate = row[5]

    locdata.close()


    self.table_locsearch.setItem(0, 0, QtWidgets.QTableWidgetItem(locid))
    self.table_locsearch.setItem(1, 0, QtWidgets.QTableWidgetItem(locname))
    self.table_locsearch.setItem(2, 0, QtWidgets.QTableWidgetItem(loccost))
    self.table_locsearch.setItem(3, 0, QtWidgets.QTableWidgetItem(locaddress))
    self.table_locsearch.setItem(4, 0, QtWidgets.QTableWidgetItem(loccity))
    self.table_locsearch.setItem(5, 0, QtWidgets.QTableWidgetItem(locstate))

2 个答案:

答案 0 :(得分:0)

您可以将CSV阅读/搜索外部化,并使其成为生成器,以便它记住上次停止的位置,即:

@staticmethod
def search_csv(path, search):
    with open(path, "r") as f:
        for row in csv.reader(f):
            if search in row:
                yield row

您现在可以将其用作搜索迭代器来遍历搜索结果。实际利用率可能取决于您如何实现系统的其余部分-最好是仅保留对当前搜索迭代器的引用(如果可用)(并且搜索字符串未更改),或者创建一个新的引用。不。例如,对您的search()方法进行就地更改以使其启用:

def search(self):
    # you could externalize the table setup as it's always static
    self.table_search.setRowCount(6)
    self.table_search.setColumnCount(1)
    self.table_search.verticalHeader().setDefaultSectionSize(20)
    self.table_search.verticalHeader().setVisible(True)
    self.table_search.setVerticalHeaderLabels([
        'Location ID:',
        'Location Name:',
        'Cost Center:',
        'Street Address:',
        'City:',
        'State:'])

    search = self.lineedit_locsearch.text().strip().upper()  # get the current search string
    search_gen = getattr(self, "_search_gen", None)  # attempt to grab the current search
    if search_gen is None or search_gen["search"] != search:  # we need a new search
        search_gen = {"generator": self.search_csv("data/loc.csv", search), 
                      "search": search}   # store the search string as well
        setattr(self, "_search_gen", search_gen)  # save it to the object
    try:
        result = next(search_gen["generator"])
    except StopIteration:  # no (more) results
        result = []  # alternatively you may show that there are no (more) results

    # to ensure validity, let's force the `result` to have at least 6 fields:
    result += [""] * (6 - len(result))  # fill the non-populated fields with empty strings

    for row in range(6):  # fill the table iteratively
        self.table_locsearch.setItem(row, 0, QtWidgets.QTableWidgetItem(result[row]))

它实质上检查当前实例上是否已经存在_search_gen字典,以及它是否包含与self.lineedit_locsearch中相同的搜索字符串-如果是,则使用现有的生成器继续搜索CSV,如果没有,它将创建一个新的CSV。无论哪种方式,生成器都用于获取(下一个)结果,然后仅填充表格。另外,我们确保结果至少包含6个字段,以便即使找到的CSV行没有全部包含6个字段,也可以正确填充表格。

例如,我不确定是否需要一直重新配置表格-也许可以在创建搜索结果窗口/面板/框架/任何内容时创建它,然后继续调用{{1 }}方法来更新结果。

最后,当您想关闭搜索时,请确保使用search()使生成器无效。还请注意,在搜索过程中,传递的文件(delattr(self, "_search_gen"))将在读取模式下保持打开状态,直到找不到更多结果或如上所述使搜索生成器无效。

答案 1 :(得分:0)

要打破循环,请尝试

breakflag = False
with open('data/loc.csv', "r") as locdata:
    reader = csv.reader(locdata)

    for row in reader:
        if breakflag:
            break
        for field in row: 
            if field == search_string: 
                locid = row[0]
                locname = row[1]
                loccost = row[2]
                locaddress = row[3]
                loccity = row[4]
                locstate = row[5]
                breakflag = True