Comprobando que una cadena coincide con una reglax y no coincide con otra -- python campo con regex camp codereview Relacionados El problema

Checking that a string matches one regex and doesn't match another


1
vote

problema

Español

Estoy usando pylint3 y flake8 para controlar la calidad del código. Sin embargo, estoy en la posición de Check-Mate, donde Styling One no se adapta al pylint o flake8 :

  if (not re.search(regexp, summary) and     not re.search(regexp2, summary)):                        return False     

Salida de flake8 :

  visually indented line with same indent as next logical line [E129]    

El retorno de movimiento no está ayudando, el error anterior aún se produce y hay una nueva lanzada por class Area { public: Area(){} ~Area(){} private: string m_Id; }; class IData { private: OGRLayer * m_Layer; public: ~IData() {} IData(OGRLayer *layer) { m_Layer = layer; } OGRLayer* getLayer(); }; OGRLayer* IData::getLayer() { return m_Layer; } class Areas { public: Areas(){} Areas(std::shared_ptr<IData> data); vector<Area> getAreas(); ~Areas(){} private: std::shared_ptr<IData> m_Data; vector<Area> m_Areas; }; Areas::Areas(std::shared_ptr<IData> data) { m_Data = data; } vector<Area> Areas::getAreas() { if(m_Data == nullptr) return vector<Area>(); // Declare variable for reading the features from a WFS layer OGRFeature *Feature; // Reset Reading (Although not necessary now because it hasnt been read yet, this is good practice before reading WFS data) m_Data->getLayer()->ResetReading(); while ((Feature = m_Data->getLayer()->GetNextFeature()) != NULL) { // Variable initialised to contain the definitions of all of the fileds in the WFS Layer OGRFeatureDefn *FeatureDefinition = m_Data->getLayer()->GetLayerDefn(); for (int i = 0; i < FeatureDefinition->GetFieldCount(); i++) { // Variable initialised to contain field data at the current index of i OGRFieldDefn *FieldDefinition = FeatureDefinition->GetFieldDefn(i); if (FieldDefinition->GetType() == OFTInteger) { std::cout << Feature->GetFieldAsInteger(i) << ","; } else if (FieldDefinition->GetType() == OFTReal) { std::cout << Feature->GetFieldAsDouble(i) << ","; } else if (FieldDefinition->GetType() == OFTString) { std::cout << Feature->GetFieldAsString(i) << ","; } else { std::cout << Feature->GetFieldAsString(i) << ","; } } // Variable initialised to contain Geometry point data for the field at the current index of i OGRGeometry *Geometry = Feature->GetGeometryRef(); if (Geometry != NULL && wkbFlatten(Geometry->getGeometryType()) == wkbPoint) { OGRPoint *Point = (OGRPoint *)Geometry; // Maybe need to limit the number of decimal places for X and Y coordinates to 2-3 std::cout << Point->getX() << "," << Point->getY() << std::endl; } else { std::cout << "No Point Geometry" << std::endl; } OGRFeature::DestroyFeature(Feature); } } struct IConnection { virtual std::shared_ptr<IData> QueryLayer(string layer) = 0; virtual int Write(IData *data) = 0; virtual void Release() = 0; IConnection() {} virtual ~IConnection() {} }; struct ImplIConnection : public IConnection { OGRDataSource *m_wfs_t; public: ImplIConnection(OGRDataSource *dataset) { m_wfs_t = dataset; } ~ImplIConnection() {} private: std::shared_ptr<IData> QueryLayer(string data); int Write(IData *data); void Release(); }; std::shared_ptr<IData> ImplIConnection::QueryLayer(string layerName) { OGRLayer *Layer = m_wfs_t->GetLayerByName(layerName.c_str()); if (Layer == NULL) { return NULL; } std::shared_ptr<IData> data(new IData(Layer)); return data; } int ImplIConnection::Write(IData *data) { return 0; } void ImplIConnection::Release() { } struct IMapServer { virtual std::shared_ptr<IConnection> OpenConnection(string url) = 0; virtual void Release() = 0; IMapServer() {} virtual ~IMapServer() {} }; struct ImplMapServer : public IMapServer { private: OGRDataSource *m_wfs_t; public: ImplMapServer() {} ~ImplMapServer() { OGRDataSource::DestroyDataSource(m_wfs_t); } void Init(void); std::shared_ptr<IConnection> OpenConnection(string url); void Release() {}; }; std::shared_ptr<IConnection> ImplMapServer::OpenConnection(string url) { m_wfs_t = OGRSFDriverRegistrar::Open(url.c_str(), true); if (m_wfs_t == NULL) { return NULL; } std::shared_ptr<ImplIConnection> connection(new ImplIConnection(m_wfs_t)); return connection; } void ImplMapServer::Init(void) { CPLSetConfigOption("CPL_DEBUG", "ON"); GDALAllRegister(); OGRRegisterAll(); } 0 :

  class Area { public:   Area(){}   ~Area(){} private:   string m_Id;  };   class IData {  private:      OGRLayer * m_Layer; public:     ~IData() {}     IData(OGRLayer *layer)     {         m_Layer = layer;     }      OGRLayer* getLayer();   };  OGRLayer* IData::getLayer() {     return m_Layer; }    class Areas  { public:      Areas(){}      Areas(std::shared_ptr<IData> data);      vector<Area>  getAreas();      ~Areas(){}  private:      std::shared_ptr<IData> m_Data;      vector<Area> m_Areas; };   Areas::Areas(std::shared_ptr<IData> data) {    m_Data = data; }  vector<Area> Areas::getAreas() {       if(m_Data == nullptr)     return vector<Area>();      // Declare variable for reading the features from a WFS layer     OGRFeature *Feature;      // Reset Reading (Although not necessary now because it hasnt been read yet, this is good practice before reading WFS data)     m_Data->getLayer()->ResetReading();      while ((Feature = m_Data->getLayer()->GetNextFeature()) != NULL)     {         // Variable initialised to contain the definitions of all of the fileds in the WFS Layer         OGRFeatureDefn *FeatureDefinition = m_Data->getLayer()->GetLayerDefn();          for (int i = 0; i < FeatureDefinition->GetFieldCount(); i++)         {             // Variable initialised to contain field data at the current index of i             OGRFieldDefn *FieldDefinition = FeatureDefinition->GetFieldDefn(i);              if (FieldDefinition->GetType() == OFTInteger)             {                 std::cout << Feature->GetFieldAsInteger(i) << ",";             }             else if (FieldDefinition->GetType() == OFTReal)             {                 std::cout << Feature->GetFieldAsDouble(i) << ",";             }             else if (FieldDefinition->GetType() == OFTString)             {                 std::cout << Feature->GetFieldAsString(i) << ",";             }             else             {                 std::cout << Feature->GetFieldAsString(i) << ",";             }         }          // Variable initialised to contain Geometry point data for the field at the current index of i         OGRGeometry *Geometry = Feature->GetGeometryRef();           if (Geometry != NULL && wkbFlatten(Geometry->getGeometryType()) == wkbPoint)         {             OGRPoint *Point = (OGRPoint *)Geometry;              // Maybe need to limit the number of decimal places for X and Y coordinates to 2-3             std::cout << Point->getX() << "," << Point->getY() << std::endl;         }         else         {             std::cout << "No Point Geometry" << std::endl;         }         OGRFeature::DestroyFeature(Feature);     }  }   struct IConnection {     virtual std::shared_ptr<IData>  QueryLayer(string layer) = 0;     virtual int                     Write(IData *data) = 0;     virtual void                    Release() = 0;     IConnection() {}     virtual ~IConnection() {} };  struct ImplIConnection : public IConnection {     OGRDataSource *m_wfs_t; public:     ImplIConnection(OGRDataSource *dataset)     {         m_wfs_t = dataset;     }     ~ImplIConnection() {} private:      std::shared_ptr<IData>  QueryLayer(string data);     int                     Write(IData *data);     void                    Release();  };  std::shared_ptr<IData> ImplIConnection::QueryLayer(string layerName) {     OGRLayer  *Layer = m_wfs_t->GetLayerByName(layerName.c_str());     if (Layer == NULL)     {         return NULL;     }       std::shared_ptr<IData> data(new IData(Layer));      return data; }   int ImplIConnection::Write(IData *data) {      return 0; }    void ImplIConnection::Release() {   }    struct IMapServer {     virtual std::shared_ptr<IConnection>           OpenConnection(string url) = 0;     virtual void                                   Release() = 0;     IMapServer() {}     virtual ~IMapServer() {}  };  struct ImplMapServer : public IMapServer {  private:     OGRDataSource *m_wfs_t; public:     ImplMapServer() {}     ~ImplMapServer()     {         OGRDataSource::DestroyDataSource(m_wfs_t);     }     void Init(void);     std::shared_ptr<IConnection>     OpenConnection(string url);     void                             Release() {}; };   std::shared_ptr<IConnection>  ImplMapServer::OpenConnection(string url) {     m_wfs_t = OGRSFDriverRegistrar::Open(url.c_str(), true);      if (m_wfs_t == NULL)     {         return NULL;     }      std::shared_ptr<ImplIConnection> connection(new ImplIConnection(m_wfs_t));      return connection; }  void ImplMapServer::Init(void) {     CPLSetConfigOption("CPL_DEBUG", "ON");     GDALAllRegister();     OGRRegisterAll(); } 1  

Salida de class Area { public: Area(){} ~Area(){} private: string m_Id; }; class IData { private: OGRLayer * m_Layer; public: ~IData() {} IData(OGRLayer *layer) { m_Layer = layer; } OGRLayer* getLayer(); }; OGRLayer* IData::getLayer() { return m_Layer; } class Areas { public: Areas(){} Areas(std::shared_ptr<IData> data); vector<Area> getAreas(); ~Areas(){} private: std::shared_ptr<IData> m_Data; vector<Area> m_Areas; }; Areas::Areas(std::shared_ptr<IData> data) { m_Data = data; } vector<Area> Areas::getAreas() { if(m_Data == nullptr) return vector<Area>(); // Declare variable for reading the features from a WFS layer OGRFeature *Feature; // Reset Reading (Although not necessary now because it hasnt been read yet, this is good practice before reading WFS data) m_Data->getLayer()->ResetReading(); while ((Feature = m_Data->getLayer()->GetNextFeature()) != NULL) { // Variable initialised to contain the definitions of all of the fileds in the WFS Layer OGRFeatureDefn *FeatureDefinition = m_Data->getLayer()->GetLayerDefn(); for (int i = 0; i < FeatureDefinition->GetFieldCount(); i++) { // Variable initialised to contain field data at the current index of i OGRFieldDefn *FieldDefinition = FeatureDefinition->GetFieldDefn(i); if (FieldDefinition->GetType() == OFTInteger) { std::cout << Feature->GetFieldAsInteger(i) << ","; } else if (FieldDefinition->GetType() == OFTReal) { std::cout << Feature->GetFieldAsDouble(i) << ","; } else if (FieldDefinition->GetType() == OFTString) { std::cout << Feature->GetFieldAsString(i) << ","; } else { std::cout << Feature->GetFieldAsString(i) << ","; } } // Variable initialised to contain Geometry point data for the field at the current index of i OGRGeometry *Geometry = Feature->GetGeometryRef(); if (Geometry != NULL && wkbFlatten(Geometry->getGeometryType()) == wkbPoint) { OGRPoint *Point = (OGRPoint *)Geometry; // Maybe need to limit the number of decimal places for X and Y coordinates to 2-3 std::cout << Point->getX() << "," << Point->getY() << std::endl; } else { std::cout << "No Point Geometry" << std::endl; } OGRFeature::DestroyFeature(Feature); } } struct IConnection { virtual std::shared_ptr<IData> QueryLayer(string layer) = 0; virtual int Write(IData *data) = 0; virtual void Release() = 0; IConnection() {} virtual ~IConnection() {} }; struct ImplIConnection : public IConnection { OGRDataSource *m_wfs_t; public: ImplIConnection(OGRDataSource *dataset) { m_wfs_t = dataset; } ~ImplIConnection() {} private: std::shared_ptr<IData> QueryLayer(string data); int Write(IData *data); void Release(); }; std::shared_ptr<IData> ImplIConnection::QueryLayer(string layerName) { OGRLayer *Layer = m_wfs_t->GetLayerByName(layerName.c_str()); if (Layer == NULL) { return NULL; } std::shared_ptr<IData> data(new IData(Layer)); return data; } int ImplIConnection::Write(IData *data) { return 0; } void ImplIConnection::Release() { } struct IMapServer { virtual std::shared_ptr<IConnection> OpenConnection(string url) = 0; virtual void Release() = 0; IMapServer() {} virtual ~IMapServer() {} }; struct ImplMapServer : public IMapServer { private: OGRDataSource *m_wfs_t; public: ImplMapServer() {} ~ImplMapServer() { OGRDataSource::DestroyDataSource(m_wfs_t); } void Init(void); std::shared_ptr<IConnection> OpenConnection(string url); void Release() {}; }; std::shared_ptr<IConnection> ImplMapServer::OpenConnection(string url) { m_wfs_t = OGRSFDriverRegistrar::Open(url.c_str(), true); if (m_wfs_t == NULL) { return NULL; } std::shared_ptr<ImplIConnection> connection(new ImplIConnection(m_wfs_t)); return connection; } void ImplMapServer::Init(void) { CPLSetConfigOption("CPL_DEBUG", "ON"); GDALAllRegister(); OGRRegisterAll(); } 2 :

  class Area { public:   Area(){}   ~Area(){} private:   string m_Id;  };   class IData {  private:      OGRLayer * m_Layer; public:     ~IData() {}     IData(OGRLayer *layer)     {         m_Layer = layer;     }      OGRLayer* getLayer();   };  OGRLayer* IData::getLayer() {     return m_Layer; }    class Areas  { public:      Areas(){}      Areas(std::shared_ptr<IData> data);      vector<Area>  getAreas();      ~Areas(){}  private:      std::shared_ptr<IData> m_Data;      vector<Area> m_Areas; };   Areas::Areas(std::shared_ptr<IData> data) {    m_Data = data; }  vector<Area> Areas::getAreas() {       if(m_Data == nullptr)     return vector<Area>();      // Declare variable for reading the features from a WFS layer     OGRFeature *Feature;      // Reset Reading (Although not necessary now because it hasnt been read yet, this is good practice before reading WFS data)     m_Data->getLayer()->ResetReading();      while ((Feature = m_Data->getLayer()->GetNextFeature()) != NULL)     {         // Variable initialised to contain the definitions of all of the fileds in the WFS Layer         OGRFeatureDefn *FeatureDefinition = m_Data->getLayer()->GetLayerDefn();          for (int i = 0; i < FeatureDefinition->GetFieldCount(); i++)         {             // Variable initialised to contain field data at the current index of i             OGRFieldDefn *FieldDefinition = FeatureDefinition->GetFieldDefn(i);              if (FieldDefinition->GetType() == OFTInteger)             {                 std::cout << Feature->GetFieldAsInteger(i) << ",";             }             else if (FieldDefinition->GetType() == OFTReal)             {                 std::cout << Feature->GetFieldAsDouble(i) << ",";             }             else if (FieldDefinition->GetType() == OFTString)             {                 std::cout << Feature->GetFieldAsString(i) << ",";             }             else             {                 std::cout << Feature->GetFieldAsString(i) << ",";             }         }          // Variable initialised to contain Geometry point data for the field at the current index of i         OGRGeometry *Geometry = Feature->GetGeometryRef();           if (Geometry != NULL && wkbFlatten(Geometry->getGeometryType()) == wkbPoint)         {             OGRPoint *Point = (OGRPoint *)Geometry;              // Maybe need to limit the number of decimal places for X and Y coordinates to 2-3             std::cout << Point->getX() << "," << Point->getY() << std::endl;         }         else         {             std::cout << "No Point Geometry" << std::endl;         }         OGRFeature::DestroyFeature(Feature);     }  }   struct IConnection {     virtual std::shared_ptr<IData>  QueryLayer(string layer) = 0;     virtual int                     Write(IData *data) = 0;     virtual void                    Release() = 0;     IConnection() {}     virtual ~IConnection() {} };  struct ImplIConnection : public IConnection {     OGRDataSource *m_wfs_t; public:     ImplIConnection(OGRDataSource *dataset)     {         m_wfs_t = dataset;     }     ~ImplIConnection() {} private:      std::shared_ptr<IData>  QueryLayer(string data);     int                     Write(IData *data);     void                    Release();  };  std::shared_ptr<IData> ImplIConnection::QueryLayer(string layerName) {     OGRLayer  *Layer = m_wfs_t->GetLayerByName(layerName.c_str());     if (Layer == NULL)     {         return NULL;     }       std::shared_ptr<IData> data(new IData(Layer));      return data; }   int ImplIConnection::Write(IData *data) {      return 0; }    void ImplIConnection::Release() {   }    struct IMapServer {     virtual std::shared_ptr<IConnection>           OpenConnection(string url) = 0;     virtual void                                   Release() = 0;     IMapServer() {}     virtual ~IMapServer() {}  };  struct ImplMapServer : public IMapServer {  private:     OGRDataSource *m_wfs_t; public:     ImplMapServer() {}     ~ImplMapServer()     {         OGRDataSource::DestroyDataSource(m_wfs_t);     }     void Init(void);     std::shared_ptr<IConnection>     OpenConnection(string url);     void                             Release() {}; };   std::shared_ptr<IConnection>  ImplMapServer::OpenConnection(string url) {     m_wfs_t = OGRSFDriverRegistrar::Open(url.c_str(), true);      if (m_wfs_t == NULL)     {         return NULL;     }      std::shared_ptr<ImplIConnection> connection(new ImplIConnection(m_wfs_t));      return connection; }  void ImplMapServer::Init(void) {     CPLSetConfigOption("CPL_DEBUG", "ON");     GDALAllRegister();     OGRRegisterAll(); } 3  
Original en ingles

I'm using pylint and flake8 to control the code quality. However I am in check-mate position, where styling one does not suit the pylint or flake8:

if (not re.search(regexp, summary) and     not re.search(regexp2, summary)):                        return False   

Output from flake8:

visually indented line with same indent as next logical line [E129]  

Moving return is not helping, the previous error still occurs and there is new one thrown by pylint:

if (not re.search(regexp, summary) and     not re.search(regexp2, summary)):                            return False   

Output from pylint:

[bad-indentation] Bad indentation. Found 8 spaces, expected 4   
     
 
 

Lista de respuestas

4
 
vote

por pep-8 , puedes ( " Las opciones aceptables en esta situación incluyen, pero no se limitan a ... ") más sangría la segunda línea de la condición:

  if(m == 2){     m += 1; }else if(m >= 3 && m%2 == 1){     m += 2; }else if(m >= 3 && m%2 == 0){     m += 1; }else{     // Number is not prime } 4  

La diferencia es que la sangría en las líneas de continuación es puramente estilística, mientras que la sangría del siguiente bloque de código tiene un significado semántico. En su caso:

  if(m == 2){     m += 1; }else if(m >= 3 && m%2 == 1){     m += 2; }else if(m >= 3 && m%2 == 0){     m += 1; }else{     // Number is not prime } 5  

Nota He movido el if(m == 2){ m += 1; }else if(m >= 3 && m%2 == 1){ m += 2; }else if(m >= 3 && m%2 == 0){ m += 1; }else{ // Number is not prime } 6 por la misma guía.

 

Per PEP-8, you can ("Acceptable options in this situation include, but are not limited to...") further indent the second line of the condition:

# Add some extra indentation on the conditional continuation line. if (this_is_one_thing         and that_is_another_thing):     do_something() 

The difference is that indentation in the continuation lines is purely stylistic, whereas indentation of the next code block has semantic meaning. In your case:

if (not re.search(regexp, summary)         and not re.search(regexp2, summary)):                        return False   

Note I have moved the and per the same guidance.

 
 
     
     

Relacionados problema

5  Realización de un procedimiento para cada formulario  ( Performing a procedure for each form edit ) 
Soy un poco nuevo para programar. Tengo algunas ediciones en mi forma, y ​​para cada edición completada tendrá que hacer un procedimiento. Actualmente, uso ...

8  Mapa-Reduce la implementación para dividir cadenas  ( Map reduce implementation for splitting strings ) 
He estado cambiando este código y no puedo hacerlo mucho mejor. Cambié un poco de la estructura, reinvemé una nueva función para dividir las cadenas que es má...

5  Regex coinciden para una cadena en una URL  ( Regex match for a string in a url ) 
Siento que hay un código repetitivo aquí. Todo lo que estoy haciendo es hacer un partido de regex básico para una cadena en la URL. Si se encuentra una coin...

6  Cómo reducir esta función de detección de archivo y hacer que sea compatible con comodines  ( How to reduce this archive detection function and make it supports wildcards ) 
La siguiente función se llama para determinar si un archivo dado es el archivo de otro archivo. También estoy buscando una forma de apoyar a los comodines. Po...

1  Nombre de la bahía Pirata y MAILER MAILER  ( Pirate bay name and magnet mailer ) 
Entonces, primera vez que trato PHP. Pensé que me gustaría establecer un objetivo para mí, dividirlo en problemas más pequeños y comenzar a andar en Google. A...

2  Función de validación de forma para reaccionar  ( Form validation function for react ) 
Necesito validar varios campos de entrada usando reaccionar. Estoy usando un bloque simple if-común para cada campo de entrada, pero me gustaría optimizar mi ...

4  Uso eficiente de la expresión regular y la manipulación de cadenas  ( Efficient use of regular expression and string manipulation ) 
La siguiente es mi solución a java vs c ++ . Creo que la forma en que he usado, la biblioteca de RE es ineficiente, y es posible erróneas, ya que estoy obten...

3  ¿Simplificar la expresión regular? (Conversión de Fracciones Unicode a Tex)  ( Simplify regular expression converting unicode fractions to tex ) 
Fondo Estoy convirtiendo el texto Unicode a tex para tipingetting. En la entrada, estoy permitiendo fracciones simples como ½ y ⅔ usando caracteres únic...

4  Resaltador de sintaxis para HTML y PHP  ( Syntax highlighter for html and php ) 
He creado una aplicación JavaScript para resaltar la sintaxis de HTML y PHP. Sé que muchos resaltadores de sintaxis están disponibles hoy en día, acabo de cre...

2  Validando múltiples parámetros por regex y longitud  ( Validating multiple parameters by regex and length ) 
Tengo un conjunto de funciones de validación que devuelven un código de respuesta junto con un mensaje de error si la validación falla. Las solicitudes pueden...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos