发现Python CSV Reader搜索字符串匹配

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (481)

又回来了另一个问题。

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

我有一个文件有两个相似的结果,例如,一个位置标记为Reddit(北)和Reddit(南)。如果我搜索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))
提问于
用户回答回答于

您可以将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

您现在可以将其用作搜索迭代器来检索搜索结果。实际利用率可能取决于您如何实现系统的其余部分 - 最好的方法是保留对当前搜索迭代器的引用(如果可用)(并且搜索字符串没有更改),或创建新的if不。例如,对您的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

扫码关注云+社区

领取腾讯云代金券