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
Hornbydd
44.9k5 gold badges42 silver badges84 bronze badges
asked May 17, 2019 at 13:56
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? 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
answered May 18, 2019 at 7:17
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).

answered May 18, 2019 at 4:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.