0

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
  • 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
    Commented May 17, 2019 at 15:39

2 Answers 2

1

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

Example:

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

giveintegers(a)
[11, 25]
giveintegers(a)[0]
11
giveintegers(a)[1]
25
int(sum(giveintegers(a))/len(giveintegers(a)))
18
1

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’):

EXPRESSION:

reclass(!text!)

CODE BLOCK:

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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