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

2024-04-26 05:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

再问一个问题。你知道吗

前言:用Qt设计器构建GUI,搜索按钮,解析csv数据,用找到的数据构建我的TableWidget。你知道吗

我有一个文件,它有两个相似的结果,例如,一个位置被标记为Reddit(North)和Reddit(South)。如果我搜索Reddit,只会显示第一个结果,但当我再次按下search按钮时,只会显示第一个结果,而不是第二个结果。你知道吗

问题:如何在第一次匹配时停止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))

Tags: csv数据fromselfforsearchstringtable
2条回答

您可以将您的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,如果不是,则创建一个新的。无论哪种方式,生成器都用于获取(下一个)结果,然后填充表。另外,我们确保结果至少有6个字段,这样即使找到的CSV行没有全部6个字段,表也可以正确填充。你知道吗

我不确定,但是,如果您需要一直重新配置表-也许您可以在创建搜索结果窗口/面板/框架/任何内容时创建它,然后继续调用search()方法来更新结果。你知道吗

最后,要关闭搜索时,请确保使用delattr(self, "_search_gen")使生成器无效。还要注意的是,传递的文件(data/loc.csv)将在搜索期间以读取模式保持打开状态,直到找不到更多的结果或如上所述使搜索生成器无效。你知道吗

要打破循环,试试这个

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

相关问题 更多 >

    热门问题