简体   繁体   English

使用列表在xlrd中搜索困难

[英]Difficulty with using Lists to search in xlrd

I am trying to write a program which takes the cells from the first column of an excel file (a last name), and search for that string within the text of the cell adjacent to it in the same row. 我正在尝试编写一个程序,该程序从excel文件的第一列(姓氏)中获取单元格,并在同一行中与其相邻的单元格的文本内搜索该字符串。

Currently, my code reads as follows: 目前,我的代码如下:

    import xlrd
workbook = xlrd.open_workbook("C:\Python27\Doc\Book3.xls")
worksheet = workbook.sheet_by_name("Sheet1")
num_rows = worksheet.nrows - 1
num_cells = worksheet.ncols - 1
curr_row = -1
while curr_row < num_rows:
    curr_row += 1
    row = worksheet.row(curr_row)
    curr_cell = 2
    while curr_cell < num_cells:
        curr_cell += 1
        cell_value = worksheet.cell_value(curr_row, curr_cell)
sh = workbook.sheet_by_index(0)     
first_col = sh.col_values(2)
second_col = sh.col_values(3)
L = [first_col]
L1 = [second_col]
for i, j in enumerate(L):
    if j in L1[i]:
        print j
    else:
        print 'no'

My code seems to "work" when I generate the lists by hand (ie just a test list of L = ['a', 'b', 'c'] and L1 = ['Today a cat a', 'Today b cat b'] etc, but when I attempt to use xlrd to create the lists all I get is a single "no" printout, which is very confusing. I assume this has something to do with either the way the lists are indexed or something else wonky with the size of the lists (16,000 names in column A, about 5,000,000 words of text in column B) 当我手动生成列表时,我的代码似乎“有效”(即仅是L = ['a','b','c']和L1 = ['Today a cat a','Today b cat b']等,但是当我尝试使用xlrd创建列表时,我得到的只是一个“否”打印输出,这非常令人困惑。我认为这与对列表建立索引的方式或其他方式有关否则列表的大小就很奇怪(A列中有16,000个名称,B列中约有5,000,000个单词)

Any help/tips that can be offered would be very much appreciated. 可以提供的任何帮助/提示将不胜感激。 I have seen lots of approaches to similar tasks around the web (and on here), but I have no idea how to integrate the different approaches into something that would be effective for me. 我已经在网络上(和此处)看到了许多用于完成类似任务的方法,但是我不知道如何将不同的方法集成到对我有效的方法中。

Many thanks 非常感谢

Give it a try: 试试看:

import xlrd

workbook = xlrd.open_workbook("input.xls")
worksheet = workbook.sheet_by_name("Sheet1")

for row in xrange(worksheet.nrows):
    value_first = worksheet.cell_value(row, 0)
    value_second = worksheet.cell_value(row, 1)
    if value_first in value_second:
        print row
    else:
        print 'no'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM