TextToFloat.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """
  2. ***************************************************************************
  3. TextToFloat.py
  4. ---------------------
  5. Date : May 2010
  6. Copyright : (C) 2010 by Michael Minn
  7. Email : pyqgis at michaelminn dot com
  8. ***************************************************************************
  9. * *
  10. * This program is free software; you can redistribute it and/or modify *
  11. * it under the terms of the GNU General Public License as published by *
  12. * the Free Software Foundation; either version 2 of the License, or *
  13. * (at your option) any later version. *
  14. * *
  15. ***************************************************************************
  16. """
  17. __author__ = 'Michael Minn'
  18. __date__ = 'May 2010'
  19. __copyright__ = '(C) 2010, Michael Minn'
  20. from qgis.PyQt.QtCore import QVariant
  21. from qgis.core import (QgsField,
  22. QgsProcessing,
  23. QgsProcessingParameterField,
  24. QgsProcessingFeatureSource)
  25. from processing.algs.qgis.QgisAlgorithm import QgisFeatureBasedAlgorithm
  26. class TextToFloat(QgisFeatureBasedAlgorithm):
  27. FIELD = 'FIELD'
  28. def group(self):
  29. return self.tr('Vector table')
  30. def groupId(self):
  31. return 'vectortable'
  32. def __init__(self):
  33. super().__init__()
  34. self.field_name = None
  35. self.field_idx = -1
  36. def initParameters(self, config=None):
  37. self.addParameter(QgsProcessingParameterField(self.FIELD,
  38. self.tr('Text attribute to convert to float'),
  39. parentLayerParameterName='INPUT',
  40. type=QgsProcessingParameterField.String
  41. ))
  42. def name(self):
  43. return 'texttofloat'
  44. def displayName(self):
  45. return self.tr('Text to float')
  46. def outputName(self):
  47. return self.tr('Float from text')
  48. def inputLayerTypes(self):
  49. return [QgsProcessing.TypeVector]
  50. def outputFields(self, inputFields):
  51. self.field_idx = inputFields.lookupField(self.field_name)
  52. if self.field_idx >= 0:
  53. inputFields[self.field_idx] = QgsField(self.field_name, QVariant.Double, '', 24, 15)
  54. return inputFields
  55. def prepareAlgorithm(self, parameters, context, feedback):
  56. self.field_name = self.parameterAsString(parameters, self.FIELD, context)
  57. return True
  58. def supportInPlaceEdit(self, layer):
  59. return False
  60. def sourceFlags(self):
  61. return QgsProcessingFeatureSource.FlagSkipGeometryValidityChecks
  62. def processFeature(self, feature, context, feedback):
  63. value = feature[self.field_idx]
  64. try:
  65. if '%' in value:
  66. feature[self.field_idx] = float(value.replace('%', '')) / 100.0
  67. else:
  68. feature[self.field_idx] = float(value)
  69. except:
  70. feature[self.field_idx] = None
  71. return [feature]