corretti problemi di pylint

c'e' da renderlo meno rompicoglioni
This commit is contained in:
2020-10-12 16:00:20 +02:00
parent e195ea5532
commit 16ab928383
6 changed files with 1248 additions and 1167 deletions

29
SPEx/poetry.lock generated
View File

@@ -34,6 +34,18 @@ docs = ["sphinx", "sphinx-rtd-theme", "zope.interface"]
tests = ["coverage (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "zope.interface"] tests = ["coverage (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "zope.interface"]
tests_no_zope = ["coverage (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six"] tests_no_zope = ["coverage (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six"]
[[package]]
category = "dev"
description = "A tool that automatically formats Python code to conform to the PEP 8 style guide"
name = "autopep8"
optional = false
python-versions = "*"
version = "1.5.4"
[package.dependencies]
pycodestyle = ">=2.6.0"
toml = "*"
[[package]] [[package]]
category = "dev" category = "dev"
description = "Cross-platform colored terminal text." description = "Cross-platform colored terminal text."
@@ -119,6 +131,14 @@ optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
version = "1.9.0" version = "1.9.0"
[[package]]
category = "dev"
description = "Python style guide checker"
name = "pycodestyle"
optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
version = "2.6.0"
[[package]] [[package]]
category = "dev" category = "dev"
description = "python code static checker" description = "python code static checker"
@@ -238,7 +258,7 @@ python-versions = "*"
version = "1.12.1" version = "1.12.1"
[metadata] [metadata]
content-hash = "e35375126d07552fb1e200007cf6bd02991d90c71eb261f21b33919e77395a58" content-hash = "f2c0aacdec9a2b08fb05b279563096aab92c78d4b64ccc312db25de8e74a910f"
lock-version = "1.0" lock-version = "1.0"
python-versions = "^3.8" python-versions = "^3.8"
@@ -255,6 +275,9 @@ attrs = [
{file = "attrs-20.2.0-py2.py3-none-any.whl", hash = "sha256:fce7fc47dfc976152e82d53ff92fa0407700c21acd20886a13777a0d20e655dc"}, {file = "attrs-20.2.0-py2.py3-none-any.whl", hash = "sha256:fce7fc47dfc976152e82d53ff92fa0407700c21acd20886a13777a0d20e655dc"},
{file = "attrs-20.2.0.tar.gz", hash = "sha256:26b54ddbbb9ee1d34d5d3668dd37d6cf74990ab23c828c2888dccdceee395594"}, {file = "attrs-20.2.0.tar.gz", hash = "sha256:26b54ddbbb9ee1d34d5d3668dd37d6cf74990ab23c828c2888dccdceee395594"},
] ]
autopep8 = [
{file = "autopep8-1.5.4.tar.gz", hash = "sha256:d21d3901cb0da6ebd1e83fc9b0dfbde8b46afc2ede4fe32fbda0c7c6118ca094"},
]
colorama = [ colorama = [
{file = "colorama-0.4.3-py2.py3-none-any.whl", hash = "sha256:7d73d2a99753107a36ac6b455ee49046802e59d9d076ef8e47b61499fa29afff"}, {file = "colorama-0.4.3-py2.py3-none-any.whl", hash = "sha256:7d73d2a99753107a36ac6b455ee49046802e59d9d076ef8e47b61499fa29afff"},
{file = "colorama-0.4.3.tar.gz", hash = "sha256:e96da0d330793e2cb9485e9ddfd918d456036c7149416295932478192f4436a1"}, {file = "colorama-0.4.3.tar.gz", hash = "sha256:e96da0d330793e2cb9485e9ddfd918d456036c7149416295932478192f4436a1"},
@@ -309,6 +332,10 @@ py = [
{file = "py-1.9.0-py2.py3-none-any.whl", hash = "sha256:366389d1db726cd2fcfc79732e75410e5fe4d31db13692115529d34069a043c2"}, {file = "py-1.9.0-py2.py3-none-any.whl", hash = "sha256:366389d1db726cd2fcfc79732e75410e5fe4d31db13692115529d34069a043c2"},
{file = "py-1.9.0.tar.gz", hash = "sha256:9ca6883ce56b4e8da7e79ac18787889fa5206c79dcc67fb065376cd2fe03f342"}, {file = "py-1.9.0.tar.gz", hash = "sha256:9ca6883ce56b4e8da7e79ac18787889fa5206c79dcc67fb065376cd2fe03f342"},
] ]
pycodestyle = [
{file = "pycodestyle-2.6.0-py2.py3-none-any.whl", hash = "sha256:2295e7b2f6b5bd100585ebcb1f616591b652db8a741695b3d8f5d28bdc934367"},
{file = "pycodestyle-2.6.0.tar.gz", hash = "sha256:c58a7d2815e0e8d7972bf1803331fb0152f867bd89adf8a01dfd55085434192e"},
]
pylint = [ pylint = [
{file = "pylint-2.6.0-py3-none-any.whl", hash = "sha256:bfe68f020f8a0fece830a22dd4d5dddb4ecc6137db04face4c3420a46a52239f"}, {file = "pylint-2.6.0-py3-none-any.whl", hash = "sha256:bfe68f020f8a0fece830a22dd4d5dddb4ecc6137db04face4c3420a46a52239f"},
{file = "pylint-2.6.0.tar.gz", hash = "sha256:bb4a908c9dadbc3aac18860550e870f58e1a02c9f2c204fdf5693d73be061210"}, {file = "pylint-2.6.0.tar.gz", hash = "sha256:bb4a908c9dadbc3aac18860550e870f58e1a02c9f2c204fdf5693d73be061210"},

View File

@@ -13,6 +13,7 @@ parse = "*"
[tool.poetry.dev-dependencies] [tool.poetry.dev-dependencies]
pytest = "^5.2" pytest = "^5.2"
pylint = "^2.6.0" pylint = "^2.6.0"
autopep8 = "^1.5.4"
[build-system] [build-system]
requires = ["poetry>=0.12"] requires = ["poetry>=0.12"]

File diff suppressed because it is too large Load Diff

View File

@@ -7,107 +7,105 @@ import json,os,glob,copy
from PyQt5.QtCore import QObject from PyQt5.QtCore import QObject
class bananaCONF(QObject): class bananaCONF(QObject):
''' '''
Carica e Salva file di configurazione per bananaSPLITTER Carica e Salva file di configurazione per bananaSPLITTER
''' '''
def __init__(self, workdir=None, logger=None): def __init__(self, workdir=None, logger=None):
try: try:
QObject.__init__(self) QObject.__init__(self)
self.log = logger self.log = logger
self.fileList = None self.fileList = None
self.workdir = None self.workdir = None
self.inUse = None self.inUse = None
self.settingsList = dict() self.settingsList = dict()
if workdir is not None: if workdir is not None:
self.workdir = workdir self.workdir = workdir
os.chdir(workdir) os.chdir(workdir)
self.log.debug(self.tr("Cerco le configurazioni in: [{}]").format(os.getcwd())) self.log.debug(self.tr("Cerco le configurazioni in: [{}]").format(os.getcwd()))
else: else:
self.log.error(self.tr("Non mi e' stata fornita una directory per i file di configurazione")) self.log.error(self.tr("Non mi e' stata fornita una directory per i file di configurazione"))
pass pass
except Exception as e: except Exception as e:
print(f"libConfload Exception: {e}") print(f"libConfload Exception: {e}")
def open(self): def open(self):
self.log.info(self.tr("Carico i file di configurazione")) self.log.info(self.tr("Carico i file di configurazione"))
self.fileList = glob.glob(r"*.json") self.fileList = glob.glob(r"*.json")
if len(self.fileList) > 0: if len(self.fileList) > 0:
for f in self.fileList: for f in self.fileList:
try: try:
fp = open(f) fp = open(f)
tf = json.load(fp) tf = json.load(fp)
fName = f.split("\\")[-1] fName = f.split("\\")[-1]
self.settingsList[fName] = copy.deepcopy(tf) self.settingsList[fName] = copy.deepcopy(tf)
self.log.info(self.tr("Caricato correttamente: {}").format(fName)) self.log.info(self.tr("Caricato correttamente: {}").format(fName))
fp.close() fp.close()
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
self.log.error(self.tr("Impossibile leggere la configurazione:{}\n \ self.log.error(self.tr("Impossibile leggere la configurazione:{}\n \
Controlla il file a riga: {} e colonna:{}").format(e.doc, e.lineno, e.colno)) Controlla il file a riga: {} e colonna:{}").format(e.doc, e.lineno, e.colno))
except IOError as ee: except IOError as ee:
self.log.error(self.tr("Impossibile aprire il file: {}").format(ee)) self.log.error(self.tr("Impossibile aprire il file: {}").format(ee))
except Exception as eee: except Exception as eee:
self.log.critical(self.tr("Eccezione inaspettata: {}").format(eee)) self.log.critical(self.tr("Eccezione inaspettata: {}").format(eee))
else: else:
self.log.error(self.tr("Non ho trovato alcun file di configurazione!")) self.log.error(self.tr("Non ho trovato alcun file di configurazione!"))
pass pass
def reload(self): def reload(self):
self.settingsList = None self.settingsList = None
self.fileList = None self.fileList = None
self.inUse = None self.inUse = None
self.open() self.open()
pass pass
def use(self, toUse): def use(self, toUse):
self.inUse = toUse self.inUse = toUse
return self return self
def save(self, fName=None): def save(self, fName=None):
if fName is None: if fName is None:
fName=self.inUse fName=self.inUse
self.log.info(self.tr("Salvo la configurazione: {}").format(fName)) self.log.info(self.tr("Salvo la configurazione: {}").format(fName))
try: try:
f=open(fName, 'w') f=open(fName, 'w')
json.dump(self.settingsList[self.inUse], f, indent='\t') json.dump(self.settingsList[self.inUse], f, indent='\t')
f.close() f.close()
except IOError as e: except IOError as e:
self.log.error(self.tr("Impossibile salvare il file: {} - [{}]").format(fName,e)) self.log.error(self.tr("Impossibile salvare il file: {} - [{}]").format(fName,e))
except Exception as ei: except Exception as ei:
self.log.error(self.tr("Errore imprevisto nella scrittura del file: {}").format(ei)) self.log.error(self.tr("Errore imprevisto nella scrittura del file: {}").format(ei))
pass pass
def getFiles(self): def getFiles(self):
return self.fileList return self.fileList
def getParam(self, *keys): def getParam(self, *keys):
rv = self.settingsList[self.inUse] rv = self.settingsList[self.inUse]
try: try:
for k in keys: for k in keys:
rv = rv[k] rv = rv[k]
return rv return rv
except ValueError as ve: except ValueError as ve:
self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve)) self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve))
return False return False
pass pass
def setParam(self, keys=(), val=None): def setParam(self, keys=(), val=None):
sv = self.settingsList[self.inUse] sv = self.settingsList[self.inUse]
try: try:
for k in keys[:-1]: for k in keys[:-1]:
sv = sv[k] sv = sv[k]
sv[keys[-1]] = val sv[keys[-1]] = val
return True return True
except ValueError as ve: except ValueError as ve:
self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve)) self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve))
return False return False
pass pass
def dump(self):
return self.settingsList[self.inUse]
def loads(self, conf):
jconf = json.loads(conf)
self.settingsList[self.inUse]=jconf
def dump(self):
return self.settingsList[self.inUse]
def loads(self, conf):
jconf = json.loads(conf)
self.settingsList[self.inUse]=jconf

View File

@@ -10,92 +10,92 @@ import colorama
from PyQt5.QtCore import QObject, pyqtSignal from PyQt5.QtCore import QObject, pyqtSignal
class fancyLogger(QObject): class fancyLogger(QObject):
''' '''
Colorizza il logger di python, per un' esperienza stile willy wonka Colorizza il logger di python, per un' esperienza stile willy wonka
''' '''
sendLog = pyqtSignal(str) sendLog = pyqtSignal(str)
def __init__(self, filepath=None, name="Logger", consoleLog=True, fileLog=False): def __init__(self, filepath=None, name="Logger", consoleLog=True, fileLog=False):
QObject.__init__(self) QObject.__init__(self)
try: try:
with open(filepath, 'r') as fp: with open(filepath, 'r') as fp:
settings = json.load(fp) settings = json.load(fp)
fp.close() fp.close()
colorama.init(convert=True) colorama.init(convert=True)
self.LRED = colorama.Fore.LIGHTRED_EX self.LRED = colorama.Fore.LIGHTRED_EX
self.RED = colorama.Fore.RED self.RED = colorama.Fore.RED
self.LYELLOW = colorama.Fore.LIGHTYELLOW_EX self.LYELLOW = colorama.Fore.LIGHTYELLOW_EX
self.YELLOW = colorama.Fore.YELLOW self.YELLOW = colorama.Fore.YELLOW
self.LBLUE = colorama.Fore.LIGHTBLUE_EX self.LBLUE = colorama.Fore.LIGHTBLUE_EX
self.BLUE = colorama.Fore.BLUE self.BLUE = colorama.Fore.BLUE
self.LGREEN = colorama.Fore.LIGHTGREEN_EX self.LGREEN = colorama.Fore.LIGHTGREEN_EX
self.LGREEN = colorama.Fore.GREEN self.LGREEN = colorama.Fore.GREEN
self.WHITE = colorama.Fore.LIGHTWHITE_EX self.WHITE = colorama.Fore.LIGHTWHITE_EX
self.RST = colorama.Style.RESET_ALL self.RST = colorama.Style.RESET_ALL
# Setup Logger # Setup Logger
self.LOGGER = logging.getLogger(name) self.LOGGER = logging.getLogger(name)
self.LOGGER.setLevel(logging.DEBUG) self.LOGGER.setLevel(logging.DEBUG)
self.LOGGER.propagate = False self.LOGGER.propagate = False
FORMATTER = logging.Formatter((settings["logFormat"]), (settings["logTimeFormat"])) FORMATTER = logging.Formatter((settings["logFormat"]), (settings["logTimeFormat"]))
if fileLog: if fileLog:
# File Logging # File Logging
fh = logging.FileHandler((settings["logFile"])) fh = logging.FileHandler((settings["logFile"]))
fh.setLevel(logging.DEBUG) fh.setLevel(logging.DEBUG)
fh.setFormatter(FORMATTER) fh.setFormatter(FORMATTER)
self.LOGGER.addHandler(fh) self.LOGGER.addHandler(fh)
if consoleLog: if consoleLog:
# Console Logging # Console Logging
cl= logging.StreamHandler(sys.stdout) cl= logging.StreamHandler(sys.stdout)
cl.setLevel(logging.DEBUG) cl.setLevel(logging.DEBUG)
cl.setFormatter(FORMATTER) cl.setFormatter(FORMATTER)
self.LOGGER.addHandler(cl) self.LOGGER.addHandler(cl)
except IOError as e: except IOError as e:
print("Impossibile caricare la configurazione del logger: [{}]".format(e)) print("Impossibile caricare la configurazione del logger: [{}]".format(e))
except Exception as ee: except Exception as ee:
print(f"libFancylogger error: {ee}") print(f"libFancylogger error: {ee}")
pass pass
def debug(self, msg="Undefined Debug"): def debug(self, msg="Undefined Debug"):
print(self.LBLUE, end='') print(self.LBLUE, end='')
self.LOGGER.debug(msg) self.LOGGER.debug(msg)
print(self.RST, end='') print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#03c2fc'>DEBUG | {msg} </br>") self.sendLog.emit(f"<FONT COLOR='#03c2fc'>DEBUG | {msg} </br>")
pass pass
def info(self, msg="Undefined Info"): def info(self, msg="Undefined Info"):
print(self.LGREEN, end='') print(self.LGREEN, end='')
self.LOGGER.info(msg) self.LOGGER.info(msg)
print(self.RST, end='') print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#6bfc03'>INFO | {msg} </br>") self.sendLog.emit(f"<FONT COLOR='#6bfc03'>INFO | {msg} </br>")
pass pass
def warn(self, msg="Undefined Warning"): def warn(self, msg="Undefined Warning"):
print(self.LYELLOW, end='') print(self.LYELLOW, end='')
self.LOGGER.warning(msg) self.LOGGER.warning(msg)
print(self.RST, end='') print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#fc9403'>WARNING | {msg} </br>") self.sendLog.emit(f"<FONT COLOR='#fc9403'>WARNING | {msg} </br>")
pass pass
def error(self, msg="Undefined Error"): def error(self, msg="Undefined Error"):
print(self.LRED, end='') print(self.LRED, end='')
self.LOGGER.error(msg) self.LOGGER.error(msg)
print(self.RST, end='') print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#ff0000'>ERROR | {msg} </br>") self.sendLog.emit(f"<FONT COLOR='#ff0000'>ERROR | {msg} </br>")
pass pass
def critical(self, msg="Undefined Critical"): def critical(self, msg="Undefined Critical"):
print(self.RED, end='') print(self.RED, end='')
self.LOGGER.critical(msg) self.LOGGER.critical(msg)
print(self.RST, end='') print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#fc03ce'>CRITICAL | {msg} </br>") self.sendLog.emit(f"<FONT COLOR='#fc03ce'>CRITICAL | {msg} </br>")
pass pass
def testColors(self): def testColors(self):
self.debug("Test Debug") self.debug("Test Debug")
self.info("Test Info") self.info("Test Info")
self.warn("Test Warning") self.warn("Test Warning")
self.error("Test Error") self.error("Test Error")
self.critical("Test Critical") self.critical("Test Critical")
pass pass

View File

@@ -10,397 +10,395 @@ import time, parse, re, copy, os, json
import traceback import traceback
class bananaSPLITTER(QObject): class bananaSPLITTER(QObject):
sendStatus = pyqtSignal(str)
def __init__(self, fileParams=None, logger=None):
try:
QObject.__init__(self)
self.fileParams = fileParams
self.log = logger
self.rawFile = None
self.status = "first"
self.contentList = list()
self.bodyCounter=0
self.duplicateNumber=0
#self.log.debug(f"Configurazione: \n {json.dumps(fileParams, indent=2)}")
if fileParams is not None:
self.log.debug(self.tr("Sto operando sul file: {}..").format(self.fileParams['name']))
self.paths = self.fileParams['paths']
self.docStruct = self.fileParams['docStruct']
self.settings = self.fileParams['settings']
self.fileName = self.fileParams['name']
self.outPath = self.paths['OUTworkPath']+slugify(self.fileName)+'/'
self.beginTime = time.time()
pass
else:
self.log.critical(self.tr("Non e' stato fornito il nome di alcun file da splittare!"))
except Exception as e:
print(f"libSplit error: {e}")
pass
sendStatus = pyqtSignal(str) def run(self):
self.log.info(self.tr("Nuovo SPLITTER su file: {}").format(self.fileName))
self.sendStatus.emit(self.tr(f"Inizio {self.fileName}"))
try:
self.openFile()
self.remEmptyLines()
if self.docStruct['fileVersNew']:
self.newSplitFile()
else:
self.splitFile()
def __init__(self, fileParams=None, logger=None): if self.settings['removeDuplicates']:
try: self.log.info(self.tr("Controllo se ci sono dei duplicati.."))
QObject.__init__(self) self.removeDuplicates()
self.fileParams = fileParams else:
self.log = logger for idx, ff in enumerate(self.contentList):
self.rawFile = None ff['duplicate']=False
self.status = "first" self.contentList[idx]=ff
self.contentList = list() self.log.warn(self.tr("Salto il controllo dei duplicati.."))
self.bodyCounter=0 # se il parse e la rimozione dei duplicati e' andata bene
self.duplicateNumber=0 # preparo e inizio il salvataggio
#self.log.debug(f"Configurazione: \n {json.dumps(fileParams, indent=2)}") if os.path.exists(self.outPath):
if fileParams is not None: if self.settings['removeOldFiles']:
self.log.debug(self.tr("Sto operando sul file: {}..").format(self.fileParams['name'])) #os.chdir(self.outPath)
self.paths = self.fileParams['paths'] for f in os.listdir(self.outPath):
self.docStruct = self.fileParams['docStruct'] os.remove(self.outPath+f)
self.settings = self.fileParams['settings'] else:
self.fileName = self.fileParams['name'] raise FileExistsError(self.tr("Non posso sovrascrivere i vecchi file, eliminali manualmente!"))
self.outPath = self.paths['OUTworkPath']+slugify(self.fileName)+'/' else:
self.beginTime = time.time() os.mkdir(self.outPath)
pass #os.chdir(self.outPath)
else: if self.settings['saveSeparateFiles']:
self.log.critical(self.tr("Non e' stato fornito il nome di alcun file da splittare!")) self.saveSeparate()
except Exception as e: if self.settings['saveBodyFile']:
print(f"libSplit error: {e}") self.saveBody()
pass self.log.info(self.tr("L'elaborazione del file ha richiesto {:4.2f} sec").format(time.time()-self.beginTime))
def run(self): except UnicodeDecodeError as ee:
self.log.info(self.tr("Nuovo SPLITTER su file: {}").format(self.fileName)) self.log.critical(self.tr("Il file [{}] contiene caratteri non compatibili con la codifica scelta! [{}]")
self.sendStatus.emit(self.tr(f"Inizio {self.fileName}")) .format(self.fileParams['name'],ee))
try: except FileExistsError as fe:
self.openFile() self.log.critical(fe)
self.remEmptyLines() except Exception as ee:
if self.docStruct['fileVersNew']: traceback.print_exc()
self.newSplitFile() self.log.warn(ee)
else: pass
self.splitFile()
if self.settings['removeDuplicates']: def openFile(self):
self.log.info(self.tr("Controllo se ci sono dei duplicati..")) try:
self.removeDuplicates() #os.chdir(self.paths["INworkPath"])
else: self.log.info(self.tr("Carico il contenuto.."))
for idx, ff in enumerate(self.contentList): fp = open(self.paths["INworkPath"]+'/'+self.fileParams['name'], mode='r', encoding=self.settings['encoding'])
ff['duplicate']=False self.rawFile = fp.readlines()
self.contentList[idx]=ff fp.close()
self.log.warn(self.tr("Salto il controllo dei duplicati..")) except IOError as e:
# se il parse e la rimozione dei duplicati e' andata bene self.log.critical(self.tr("Impossibile aprire il file: {}! [{}]").format(self.fileName,e))
# preparo e inizio il salvataggio raise BaseException("OpenFile")
if os.path.exists(self.outPath): os.rmdir(self.outPath)
if self.settings['removeOldFiles']: except Exception as ee:
#os.chdir(self.outPath) print(ee)
for f in os.listdir(self.outPath): pass
os.remove(self.outPath+f)
else:
raise FileExistsError(self.tr("Non posso sovrascrivere i vecchi file, eliminali manualmente!"))
else:
os.mkdir(self.outPath)
#os.chdir(self.outPath)
if self.settings['saveSeparateFiles']:
self.saveSeparate()
if self.settings['saveBodyFile']:
self.saveBody()
self.log.info(self.tr("L'elaborazione del file ha richiesto {:4.2f} sec").format(time.time()-self.beginTime))
except UnicodeDecodeError as ee: def remEmptyLines(self):
self.log.critical(self.tr("Il file [{}] contiene caratteri non compatibili con la codifica scelta! [{}]") self.log.info(self.tr("Elimino righe vuote e caratteri inutili.."))
.format(self.fileParams['name'],ee)) tempContent = []
except FileExistsError as fe: try:
self.log.critical(fe) for ll in self.rawFile:
except Exception as ee: for c in self.settings['delChars']:
traceback.print_exc() ll = ll.replace(c,'')
self.log.warn(ee) if ll not in ['\n', '\r', '\r\n']:
pass tempContent.append(ll)
self.rawFile = copy.deepcopy(tempContent)
self.rawFile.append('\n') #linea vuota finale per essere sicuri di parsare bene
return True
except:
self.log.error(self.tr("Errore inaspettato durante l'eliminazione delle righe vuote!"))
raise BaseException("DelLines")
del tempContent
def openFile(self): def newSplitFile(self): #porting del codice dal programma originale
try: self.log.info(self.tr("Individuo il contenuto.."))
#os.chdir(self.paths["INworkPath"]) self.bodyCounter=0
self.log.info(self.tr("Carico il contenuto..")) self.duplicateNumber=0
fp = open(self.paths["INworkPath"]+'/'+self.fileParams['name'], mode='r', encoding=self.settings['encoding']) docNumber = 0
self.rawFile = fp.readlines() docSkipped = 0
fp.close() docDate = {}
except IOError as e: title = ''
self.log.critical(self.tr("Impossibile aprire il file: {}! [{}]").format(self.fileName,e)) prevLine = ''
raise BaseException("OpenFile") newsPaperName = ''
os.rmdir(self.outPath) titleBegin = True
except Exception as ee: newsName = False
print(ee) tempBody = list()
pass
def remEmptyLines(self): for l in self.rawFile: #per ogni linea del file
self.log.info(self.tr("Elimino righe vuote e caratteri inutili..")) l=l.replace('\xa0', ' ')
tempContent = [] lineWords = l.lstrip().split(' ') #dividi la riga in parole
try: if self.status == 'first':
for ll in self.rawFile: try:
for c in self.settings['delChars']: # ricerco la data
ll = ll.replace(c,'') if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']:
if ll not in ['\n', '\r', '\r\n']: try:
tempContent.append(ll) docDate=parse.parse(self.docStruct['dateFormat'],l).named
self.rawFile = copy.deepcopy(tempContent) docDate['month']=docDate['month'].lstrip().rstrip().capitalize()
self.rawFile.append('\n') #linea vuota finale per essere sicuri di parsare bene docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1
return True # dopo la data inizia il titolo, ma prima si cerca il nome del giornale
except: except:
self.log.error(self.tr("Errore inaspettato durante l'eliminazione delle righe vuote!")) self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]"). format(l.strip('\r\n')))
raise BaseException("DelLines") pass
del tempContent elif lineWords[0].upper() in self.docStruct['language']['headWords']:
#cambio stato e inizializzo un nuovo documento da riempire
self.status = 'head'
newDoc=dict()
newDoc['title']=title
newDoc['date']=docDate
newDoc['newsPaperName'] = newsPaperName
titleBegin = False
newsName = False
else:
if titleBegin:
title = l.strip().capitalize()
titleBegin = False
newsName = True
elif newsName:
if self.settings['getNewsPaperName']:
try:
if l.strip():
newsPaperName = l.strip()
else:
newsPaperName = self.settings['nameNotFoundStr']
except:
self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\
controlla i file di uscita! [{}]").format(l.strip()))
else:
newsPaperName = self.settings['nameNotFoundStr']
newsName = False
except IndexError:
self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!"))
pass
elif self.status == 'head':
tempContent = list()
#doppio check per trovare l'inizio del corpo documento
if re.match(self.docStruct['beginOfDocument'],l):
self.status='body'
#if lineWords[0].upper() not in self.docStruct['language']['headWords']: #se la prima parola non e' tra quelle di inizio
#tempBody.append(l) # vuol dire che ho trovato l'articolo e aggiungo la prima riga al contenuto del documento
#self.status = 'body'
elif self.status == 'body':
if re.match(self.docStruct['endOfDocument'],l) is not None: #controlla se ci sono articoli che non hanno le parole chiave finali
self.log.warn(self.tr("Ho individuato una separatore valido prima che si chiusesse l'articolo precedente, controlla i tuoi file in uscita!\n\
L'errore dovrebbe essere intorno all'articolo {} ma non sono sicuro! \n\t\t\t[{}]").format(docNumber, l.strip()))
self.status = 'tail'
anomaly = True
elif not lineWords[0].upper() in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine
if self.settings['delLF']:
tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo
else:
tempBody.append(l)
else:
self.status = 'tail'
anomaly = False
def newSplitFile(self): #porting del codice dal programma originale pass
self.log.info(self.tr("Individuo il contenuto..")) elif self.status == 'tail':
self.bodyCounter=0 if anomaly or (re.match(self.docStruct['endOfDocument'],l) is not None):
self.duplicateNumber=0 self.status = 'first'
docNumber = 0 anomaly = False
docSkipped = 0 titleBegin = True
docDate = {} if self.settings['delWordBreak']:
title = '' tempContent=[ll.replace('-\n', '') for ll in tempContent]
prevLine = '' newDoc['content']=copy.deepcopy(''.join(tempBody))
newsPaperName = '' self.contentList.append(copy.deepcopy(newDoc))
titleBegin = True tempBody=list()
newsName = False self.bodyCounter +=1
tempBody = list() pass
else:
self.log.critical(self.tr("Stato Interno Sconosciuto"))
prevLine=l #salva sempre e comunque il contenuto della linea precedente
pass
#ricerca terminata, espongo i risultati
self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter))
if docSkipped > 0:
self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped))
pass
pass
for l in self.rawFile: #per ogni linea del file def splitFile(self): #porting del codice dal programma originale
l=l.replace('\xa0', ' ') self.log.info(self.tr("Individuo il contenuto.."))
lineWords = l.lstrip().split(' ') #dividi la riga in parole self.bodyCounter=0
if self.status == 'first': self.duplicateNumber=0
try: docNumber = 0
# ricerco la data docSkipped = 0
if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']: docDate = {}
try: title = ''
docDate=parse.parse(self.docStruct['dateFormat'],l).named prevLine = ''
docDate['month']=docDate['month'].lstrip().rstrip().capitalize() newsPaperName = ''
docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1 titleBegin = False
# dopo la data inizia il titolo, ma prima si cerca il nome del giornale tempBody = list()
except: docSep=re.compile(self.docStruct['docSep'])
self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]"). format(l.strip('\r\n')))
pass
elif lineWords[0].upper() in self.docStruct['language']['headWords']:
#cambio stato e inizializzo un nuovo documento da riempire
self.status = 'head'
newDoc=dict()
newDoc['title']=title
newDoc['date']=docDate
newDoc['newsPaperName'] = newsPaperName
titleBegin = False
newsName = False
else:
if titleBegin:
title = l.strip().capitalize()
titleBegin = False
newsName = True
elif newsName:
if self.settings['getNewsPaperName']:
try:
if l.strip():
newsPaperName = l.strip()
else:
newsPaperName = self.settings['nameNotFoundStr']
except:
self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\
controlla i file di uscita! [{}]").format(l.strip()))
else:
newsPaperName = self.settings['nameNotFoundStr']
newsName = False
except IndexError:
self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!"))
pass
elif self.status == 'head':
tempContent = list()
#doppio check per trovare l'inizio del corpo documento
if re.match(self.docStruct['beginOfDocument'],l):
self.status='body'
#if lineWords[0].upper() not in self.docStruct['language']['headWords']: #se la prima parola non e' tra quelle di inizio
#tempBody.append(l) # vuol dire che ho trovato l'articolo e aggiungo la prima riga al contenuto del documento
#self.status = 'body'
elif self.status == 'body':
if re.match(self.docStruct['endOfDocument'],l) is not None: #controlla se ci sono articoli che non hanno le parole chiave finali
self.log.warn(self.tr("Ho individuato una separatore valido prima che si chiusesse l'articolo precedente, controlla i tuoi file in uscita!\n\
L'errore dovrebbe essere intorno all'articolo {} ma non sono sicuro! \n\t\t\t[{}]").format(docNumber, l.strip()))
self.status = 'tail'
anomaly = True
elif not lineWords[0].upper() in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine
if self.settings['delLF']:
tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo
else:
tempBody.append(l)
else:
self.status = 'tail'
anomaly = False
pass for l in self.rawFile: #per ogni linea del file
elif self.status == 'tail': lineWords = l.lstrip().split(' ') #dividi la riga in parole
if anomaly or (re.match(self.docStruct['endOfDocument'],l) is not None): if self.status == 'first':
self.status = 'first' #prendo il numero di documento per vedere se ci sono buchi
anomaly = False try:
titleBegin = True try:
if self.settings['delWordBreak']: nn = parse.parse("{current:d} Of {total} Documents",l.strip().capitalize()).named
tempContent=[ll.replace('-\n', '') for ll in tempContent] if nn["current"]-docNumber==1:
newDoc['content']=copy.deepcopy(''.join(tempBody)) pass
self.contentList.append(copy.deepcopy(newDoc)) else:
tempBody=list() if self.settings["showSkipped"]:
self.bodyCounter +=1 self.log.warn(self.tr("Il conto dei documenti non torna! LexisNexis ne ha saltato qualcuno!\n Precedente:{0}-Attuale:{1}").format(docNumber,nn["current"]))
pass docSkipped+=1
else: docNumber = nn["current"]
self.log.critical(self.tr("Stato Interno Sconosciuto")) except:
prevLine=l #salva sempre e comunque il contenuto della linea precedente pass #non segnalare eccezione se il parse fallisce
pass # ricerco la data
#ricerca terminata, espongo i risultati if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']:
self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter)) try:
if docSkipped > 0: docDate=parse.parse(self.docStruct['dateFormat'],l).named
self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped)) docDate['month']=docDate['month'].lstrip().rstrip().capitalize()
pass docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1
pass title = ''
titleBegin=True
# dopo la data inizia il titolo, ma prima si cerca il nome del giornale
if self.settings['getNewsPaperName']:
try:
if prevLine.split(' ')[0].strip().isalpha():
newsPaperName = prevLine.strip()
else:
newsPaperName = self.settings['nameNotFoundStr']
except:
self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\
controlla i file di uscita! [{}]").format(prevLine.strip()))
else:
newsPaperName = self.settings['nameNotFoundStr']
except:
self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]").format(l.strip('\r\n')))
pass
elif lineWords[0] in self.docStruct['language']['headWords']:
#cambio stato e inizializzo un nuovo documento da riempire
self.status = 'head'
newDoc=dict()
newDoc['title']=title
newDoc['date']=docDate
newDoc['newsPaperName'] = newsPaperName
titleBegin=False
else:
if titleBegin:
title += l.strip().capitalize()
except IndexError:
self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!"))
pass
elif self.status == 'head':
tempContent = list()
if lineWords[0] not in self.docStruct['language']['headWords']: #se la prima parola non e' tra quelle di inizio
tempBody.append(l) # vuol dire che ho trovato l'articolo e aggiungo la prima riga al contenuto del documento
self.status = 'body'
pass
elif self.status == 'body':
if not lineWords[0] in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine
if self.settings['delLF']:
tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo
else:
tempBody.append(l)
else:
self.status = 'tail'
anomaly = False
if docSep.match(l) is not None: #controlla se ci sono articoli che non hanno le parole chiave finali
self.log.warn(self.tr("Ho individuato una separatore valido prima che si chiusesse l'articolo precedente, controlla i tuoi file in uscita!\n\
L'errore dovrebbe essere intorno all'articolo {} ma non sono sicuro! \n\t\t[{}]").format(docNumber, l.strip()))
self.status = 'tail'
anomaly = True
pass
elif self.status == 'tail':
if docSep.match(l) is not None or anomaly:
self.status = 'first'
anomaly = False
if self.settings['delWordBreak']:
tempContent=[ll.replace('-\n', '') for ll in tempContent]
newDoc['content']=copy.deepcopy(''.join(tempBody))
self.contentList.append(copy.deepcopy(newDoc))
tempBody=list()
self.bodyCounter +=1
pass
else:
self.log.critical(self.tr("Stato Interno Sconosciuto"))
prevLine=l #salva sempre e comunque il contenuto della linea precedente
pass
#ricerca terminata, espongo i risultati
self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter))
if docSkipped > 0:
self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped))
pass
pass
def splitFile(self): #porting del codice dal programma originale def removeDuplicates(self):
self.log.info(self.tr("Individuo il contenuto..")) titleList=[]
self.bodyCounter=0 duplicateList=[]
self.duplicateNumber=0 for idx, ff in enumerate(self.contentList):
docNumber = 0 if ff['title'] not in titleList:
docSkipped = 0 titleList.append(ff['title'])
docDate = {} ff['duplicate']=False
title = '' self.contentList[idx]=ff
prevLine = '' pass
newsPaperName = '' else:
titleBegin = False if ff['title'] not in duplicateList:
tempBody = list() duplicateList.append(ff['title'])
docSep=re.compile(self.docStruct['docSep']) if self.settings['showRemovedDuplicates']:
self.log.info(self.tr("Duplicato: {}").format(ff['title'].strip()))
ff['duplicate'] = True
self.contentList[idx]=ff
self.duplicateNumber+=1
self.log.info(self.tr("Ho rimosso {} duplicati di {} articoli..").format(self.duplicateNumber, len(duplicateList)))
pass
for l in self.rawFile: #per ogni linea del file def saveSeparate(self):
lineWords = l.lstrip().split(' ') #dividi la riga in parole outFileCounter = 0
if self.status == 'first': self.paths['OUTworkPath']=self.paths['OUTworkPath']+slugify(self.fileName)
#prendo il numero di documento per vedere se ci sono buchi self.log.info(self.tr("Salvo gli articoli in file separati..."))
try: self.log.debug(self.tr("Persorso: {0}").format(self.outPath))
try: for ff in self.contentList:
nn = parse.parse("{current:d} Of {total} Documents",l.strip().capitalize()).named try:
if nn["current"]-docNumber==1: if ff['duplicate'] == False:
pass fName=self.docStruct['outNameFormat'].format(title=slugify(ff['title'][:self.docStruct['maxTitleLen']]),\
else: filename=slugify(self.fileName),\
if self.settings["showSkipped"]: docnum=outFileCounter,\
self.log.warn(self.tr("Il conto dei documenti non torna! LexisNexis ne ha saltato qualcuno!\n Precedente:{0}-Attuale:{1}").format(docNumber,nn["current"])) papername=ff['newsPaperName'].strip(),\
docSkipped+=1 **ff['date'])
docNumber = nn["current"] out=open(self.outPath+'{0}'.format(fName),'wb')
except: if self.settings['includeTitle']:
pass #non segnalare eccezione se il parse fallisce ff['content'] = ff['title']+os.linesep+ff['content']
# ricerco la data out.write(ff['content'].encode(self.settings['encoding']))
if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']: out.close()
try: outFileCounter+=1
docDate=parse.parse(self.docStruct['dateFormat'],l).named except IOError as e:
docDate['month']=docDate['month'].lstrip().rstrip().capitalize() self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e))
docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1 continue
title = '' except KeyError as ke:
titleBegin=True self.log.error(self.tr(f"Chiave {ke} non trovata per:{outFileCounter} {ff['title']} "))
# dopo la data inizia il titolo, ma prima si cerca il nome del giornale except Exception as ee:
if self.settings['getNewsPaperName']: traceback.print_exc()
try: self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}"))
if prevLine.split(' ')[0].strip().isalpha(): if outFileCounter < self.bodyCounter:
newsPaperName = prevLine.strip() self.log.error(self.tr("Ho salvato meno file rispetto a quelli trovati!"))
else: pass
newsPaperName = self.settings['nameNotFoundStr']
except:
self.log.warn(self.tr("E' successo qualcosa mentre stavo cercando il nome della pubblicazione,\
controlla i file di uscita! [{}]").format(prevLine.strip()))
else:
newsPaperName = self.settings['nameNotFoundStr']
except:
self.log.warn(self.tr("Ho trovato una riga ambigua.. potrebbe essere una data ma non so: [{}]").format(l.strip('\r\n')))
pass
elif lineWords[0] in self.docStruct['language']['headWords']:
#cambio stato e inizializzo un nuovo documento da riempire
self.status = 'head'
newDoc=dict()
newDoc['title']=title
newDoc['date']=docDate
newDoc['newsPaperName'] = newsPaperName
titleBegin=False
else:
if titleBegin:
title += l.strip().capitalize()
except IndexError:
self.log.error(self.tr("Errore inaspettato, contatta il tuo sviluppatore di fiducia!"))
pass
elif self.status == 'head':
tempContent = list()
if lineWords[0] not in self.docStruct['language']['headWords']: #se la prima parola non e' tra quelle di inizio
tempBody.append(l) # vuol dire che ho trovato l'articolo e aggiungo la prima riga al contenuto del documento
self.status = 'body'
pass
elif self.status == 'body':
if not lineWords[0] in self.docStruct['language']['tailWords']: #se la prima parola non e' tra quelle di fine
if self.settings['delLF']:
tempBody.append(l.strip('\n')) #allora sto leggendo l'articolo
else:
tempBody.append(l)
else:
self.status = 'tail'
anomaly = False
if docSep.match(l) is not None: #controlla se ci sono articoli che non hanno le parole chiave finali
self.log.warn(self.tr("Ho individuato una separatore valido prima che si chiusesse l'articolo precedente, controlla i tuoi file in uscita!\n\
L'errore dovrebbe essere intorno all'articolo {} ma non sono sicuro! \n\t\t[{}]").format(docNumber, l.strip()))
self.status = 'tail'
anomaly = True
pass
elif self.status == 'tail':
if docSep.match(l) is not None or anomaly:
self.status = 'first'
anomaly = False
if self.settings['delWordBreak']:
tempContent=[ll.replace('-\n', '') for ll in tempContent]
newDoc['content']=copy.deepcopy(''.join(tempBody))
self.contentList.append(copy.deepcopy(newDoc))
tempBody=list()
self.bodyCounter +=1
pass
else:
self.log.critical(self.tr("Stato Interno Sconosciuto"))
prevLine=l #salva sempre e comunque il contenuto della linea precedente
pass
#ricerca terminata, espongo i risultati
self.log.info(self.tr("Nel file ho trovato {0} articoli..").format(self.bodyCounter))
if docSkipped > 0:
self.log.warn(self.tr("Attentione, LexisNexis ne ha saltati {} !!!").format(docSkipped))
pass
pass
def removeDuplicates(self): def saveBody(self):
titleList=[] self.log.info(self.tr('Salvo gli articoli in un singolo file vicino agli originali...'))
duplicateList=[] self.log.debug(self.tr('Persorso: {0}').format(self.outPath))
for idx, ff in enumerate(self.contentList): #os.chdir(self.outPath)
if ff['title'] not in titleList: try:
titleList.append(ff['title']) fName=slugify(self.fileName)
ff['duplicate']=False fName='BODYFILE_{0}.txt'.format(fName[:self.docStruct['maxTitleLen']])
self.contentList[idx]=ff fileContent = os.linesep.join([cc['content'] for cc in self.contentList])
pass out=open(self.outPath+'{0}'.format(fName),'wb')
else: out.write(fileContent.encode(self.settings['encoding']))
if ff['title'] not in duplicateList: out.close()
duplicateList.append(ff['title']) except IOError as e:
if self.settings['showRemovedDuplicates']: self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e))
self.log.info(self.tr("Duplicato: {}").format(ff['title'].strip())) except Exception as ee:
ff['duplicate'] = True self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}"))
self.contentList[idx]=ff pass
self.duplicateNumber+=1
self.log.info(self.tr("Ho rimosso {} duplicati di {} articoli..").format(self.duplicateNumber, len(duplicateList)))
pass
def saveSeparate(self):
outFileCounter = 0
self.paths['OUTworkPath']=self.paths['OUTworkPath']+slugify(self.fileName)
self.log.info(self.tr("Salvo gli articoli in file separati..."))
self.log.debug(self.tr("Persorso: {0}").format(self.outPath))
for ff in self.contentList:
try:
if ff['duplicate'] == False:
fName=self.docStruct['outNameFormat'].format(title=slugify(ff['title'][:self.docStruct['maxTitleLen']]),\
filename=slugify(self.fileName),\
docnum=outFileCounter,\
papername=ff['newsPaperName'].strip(),\
**ff['date'])
out=open(self.outPath+'{0}'.format(fName),'wb')
if self.settings['includeTitle']:
ff['content'] = ff['title']+os.linesep+ff['content']
out.write(ff['content'].encode(self.settings['encoding']))
out.close()
outFileCounter+=1
except IOError as e:
self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e))
continue
except KeyError as ke:
self.log.error(self.tr(f"Chiave {ke} non trovata per:{outFileCounter} {ff['title']} "))
except Exception as ee:
traceback.print_exc()
self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}"))
if outFileCounter < self.bodyCounter:
self.log.error(self.tr("Ho salvato meno file rispetto a quelli trovati!"))
pass
def saveBody(self):
self.log.info(self.tr('Salvo gli articoli in un singolo file vicino agli originali...'))
self.log.debug(self.tr('Persorso: {0}').format(self.outPath))
#os.chdir(self.outPath)
try:
fName=slugify(self.fileName)
fName='BODYFILE_{0}.txt'.format(fName[:self.docStruct['maxTitleLen']])
fileContent = os.linesep.join([cc['content'] for cc in self.contentList])
out=open(self.outPath+'{0}'.format(fName),'wb')
out.write(fileContent.encode(self.settings['encoding']))
out.close()
except IOError as e:
self.log.error(self.tr("Qualcosa e\' andato storto, non riesco a scrivere il file: {}").format(e))
except Exception as ee:
self.log.error(self.tr(f"Errore generale nel salvataggio: {ee}"))
pass