按特定单词筛选Excel文件中的行

2024-04-26 14:13:57 发布

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

我一直在努力设计一个python代码来在excel文件中搜索“N”字。如果存在“N”个单词,python代码应该输出这些单词所在的整行。我正在excel文件中搜索多个单词。在

假设有一个这种类型的excel文件(假设它被称为File.xlsx):

ID    Date        Time      Comment
123   12/23/2017  11:10:02 Trouble with pin
98y   01/17/2016  12:45:01 Great web experience. But I had some issues.
76H   05/39/2017  09:55:59 Could not log into the portal.

根据上述数据,问题是:
如果我要搜索单词'pin'和'log'并在上面的excel文件中找到它,我希望python代码输出第1行和它下面的输出行3。在

从概念上讲,我可以想出解决这个问题的方法,但是Python实现让我困惑不解。此外,我已经广泛搜索了堆栈溢出,但找不到一篇文章来解决这个问题。在

我们非常感谢您的任何帮助。在


Tags: 文件代码logid类型datetimewith
2条回答

有很多方法可以实现这一点,因为有许多python包可以读取Excel文件(http://www.python-excel.org/),但是xlrd可能是最直接的方法:

import xlrd                             # package to read Excel file

book = xlrd.open_workbook("File.xls")   # open the file
sh = book.sheet_by_index(0)             # get first Excel sheet

words = ['pin', 'log']                  # list of words to search

for rx in xrange(sh.nrows):             # for each row in file
    for word in words:                  # for each word in list
        if word in str(sh.row(rx)):     # check of word in row
            print 'line',rx             # if so, print row number

输出:

^{pr2}$

这是一个使用openpyxl模块的解决方案,我已经成功地在许多项目中使用过了。在

行索引从一个包含头的索引开始,因此,如果您不想对头进行计数,则需要将索引计数减少1row - 1

from openpyxl import load_workbook

wb = load_workbook(filename = 'afile.xlsx')
ws = wb.active
search_words = ['pin' , 'log']

for row in xrange(1,ws.max_row + 1):
    for col in xrange(1,ws.max_column + 1):
        _cell = ws.cell(row=row, column=col)
        if any(word in str(_cell.value) for word in search_words):
            print "line {}".format(row - 1)
            break
>>> 
line 1
line 3

如果你想输出实际的行 只需添加以下print_row函数

^{pr2}$

并将print "line {}".format(row - 1)替换为print print_row(row)

>>> 
 123 2017-12-23 00:00:00 11:10:02 Trouble with pin
 76H 05/39/2017 09:55:59 Could not log into the portal.
>>> 

相关问题 更多 >