Search code examples
pythondictionaryxlrd

Python returns TypeError: slice indices must be integers or None or have an __index__ method when searching for a key from a dictionary in a string


I have this code that imports strings from an Excel file. After importing every cell of that file, the data is stored into a 2d array named data[col][row] I have to define a dictionary that contains keys that can be found in the cells. One cell can contain multiple keys inside, and the code has to recognize all of them.

import xlrd
book = xlrd.open_workbook("c:/Users/uids3896/desktop/VWexport.xlsx")
print ("The number of worksheets is", book.nsheets)
print ("Worksheet name(s):", book.sheet_names())
sh = book.sheet_by_index(0)
print (sh.name, sh.nrows, sh.ncols)
print ("Cell D30 is", sh.cell_value(rowx=29, colx=3))
data = [[sh.cell_value(r, c) for c in range(sh.ncols)] for r in range(sh.nrows)]

def issa(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

dict={ 'ID' : 'this would be the return for ID '}
dict['1. Press  BT1 button for T= T_SHORT'] =  'this would be the return for BT1SHORTPRESS'
for col in range (sh.ncols):
    for row in range(sh.nrows):
        for key in dict.keys():
            a=data[col][row]
            s=issa(data[col][row])
            if s:
                c=1
            else:
                if a.find(a, key):
                    print (key)

But when I run the code it gives me:

Traceback (most recent call last):
File "C:\Users\uids3896\Desktop\New Text Document.py", line 34, in <module>
if a.find(a, key):
TypeError: slice indices must be integers or None or have an __index__ method

How to properly search if a string contains a key, and not only one, how to check for all of them, and concatenate the coresponding string from the dictionary in the order they occur in the string?


Solution

  • "How to properly search if a key contains a key?"

    If by that you mean "How to check if a dictionary key is present in a string:

    for key in dict.keys():
    ... 
        if key in string: <do stuff>
    

    That's because both your keys are strings.

    If you want to check that any element of the dictionary's keys is present in the string:

    if any(x in str(a) for x in list(dict.keys())): 
    

    Example

    test_string = 'This is a test string 1. Press  BT1 button for T= T_SHORT testeteditesttest ID blablah'
    dict={ 'ID' : 'this would be the return for ID '}
    dict['1. Press  BT1 button for T= T_SHORT'] =  'this would be the return for BT1SHORTPRESS'
    any(x in test_string for x in list(dict.keys()))
    

    After going over the q&a below, here's how I would do it:

    for col in range (sh.ncols):
        for row in range(sh.nrows):
            # Moved reading the value fron col/row out of the for because it made no sense to read it for every key in the dict
            a=data[col][row]
            for key in dict.keys():
                s=issa(data[col][row])
                if s:
                    c=1
                else:
                     if key in a:
                        a = a.replace(key, dict[key])
            data[col][row] = a
            <save and close the excel or do other things to it>