So I am trying to reclassify a text string by searching for bits of strings and converting those strings to an integer value in a new field within the field calculator. e.g. I want to find all values in the field "text" that contain the word "cover" in them, for example, "Other deciduous trees with 11- 25% impervious cover". I then want to take that and assign an integer value to a new field "class". I tried to write the script (shown below), but no dice so far, anyone have any insight?

def reclass(C_TEXT):
if "cover" in C_TEXT:
    return 10
  • 1
    You may want to add a little more code to your question. Show how the function is being called, and how the return value is used. Is the "class" field an integer or text type? – Bjorn May 17 '19 at 15:39

You can use re module, see How to extract numbers from a string in Python?


import re
a = "Other deciduous trees with 11- 25% impervious cover"

def giveintegers(data):
    if 'cover' in data:
        integers = [int(s) for s in re.findall(r'\b\d+\b', data)]
        return integers

[11, 25]
| improve this answer | |

You haven’t posted the rest of your field calculator. But you code block looks OK. Some minor changes below may help, and you would need an expression some thing like this (assuming a field name of ‘text’):




def reclass(C_TEXT):
    if "cover" in C_TEXT.lower():
        return 10
    return None

The last line isn’t strictly necessary, but I prefer it to make it obvious what is happening.

The ‘.lower()’ makes it case insensitive (ie, compares a lowercase string literal to the lowercase version of the C_TEXT value).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.