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_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]]
category = "dev"
description = "Cross-platform colored terminal text."
@@ -119,6 +131,14 @@ optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
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]]
category = "dev"
description = "python code static checker"
@@ -238,7 +258,7 @@ python-versions = "*"
version = "1.12.1"
[metadata]
content-hash = "e35375126d07552fb1e200007cf6bd02991d90c71eb261f21b33919e77395a58"
content-hash = "f2c0aacdec9a2b08fb05b279563096aab92c78d4b64ccc312db25de8e74a910f"
lock-version = "1.0"
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.tar.gz", hash = "sha256:26b54ddbbb9ee1d34d5d3668dd37d6cf74990ab23c828c2888dccdceee395594"},
]
autopep8 = [
{file = "autopep8-1.5.4.tar.gz", hash = "sha256:d21d3901cb0da6ebd1e83fc9b0dfbde8b46afc2ede4fe32fbda0c7c6118ca094"},
]
colorama = [
{file = "colorama-0.4.3-py2.py3-none-any.whl", hash = "sha256:7d73d2a99753107a36ac6b455ee49046802e59d9d076ef8e47b61499fa29afff"},
{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.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 = [
{file = "pylint-2.6.0-py3-none-any.whl", hash = "sha256:bfe68f020f8a0fece830a22dd4d5dddb4ecc6137db04face4c3420a46a52239f"},
{file = "pylint-2.6.0.tar.gz", hash = "sha256:bb4a908c9dadbc3aac18860550e870f58e1a02c9f2c204fdf5693d73be061210"},

View File

@@ -13,6 +13,7 @@ parse = "*"
[tool.poetry.dev-dependencies]
pytest = "^5.2"
pylint = "^2.6.0"
autopep8 = "^1.5.4"
[build-system]
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
class bananaCONF(QObject):
'''
Carica e Salva file di configurazione per bananaSPLITTER
'''
def __init__(self, workdir=None, logger=None):
try:
QObject.__init__(self)
self.log = logger
self.fileList = None
self.workdir = None
self.inUse = None
self.settingsList = dict()
if workdir is not None:
self.workdir = workdir
os.chdir(workdir)
self.log.debug(self.tr("Cerco le configurazioni in: [{}]").format(os.getcwd()))
else:
self.log.error(self.tr("Non mi e' stata fornita una directory per i file di configurazione"))
pass
except Exception as e:
print(f"libConfload Exception: {e}")
'''
Carica e Salva file di configurazione per bananaSPLITTER
'''
def __init__(self, workdir=None, logger=None):
try:
QObject.__init__(self)
self.log = logger
self.fileList = None
self.workdir = None
self.inUse = None
self.settingsList = dict()
if workdir is not None:
self.workdir = workdir
os.chdir(workdir)
self.log.debug(self.tr("Cerco le configurazioni in: [{}]").format(os.getcwd()))
else:
self.log.error(self.tr("Non mi e' stata fornita una directory per i file di configurazione"))
pass
except Exception as e:
print(f"libConfload Exception: {e}")
def open(self):
self.log.info(self.tr("Carico i file di configurazione"))
self.fileList = glob.glob(r"*.json")
if len(self.fileList) > 0:
for f in self.fileList:
try:
fp = open(f)
tf = json.load(fp)
fName = f.split("\\")[-1]
self.settingsList[fName] = copy.deepcopy(tf)
self.log.info(self.tr("Caricato correttamente: {}").format(fName))
fp.close()
except json.JSONDecodeError as e:
self.log.error(self.tr("Impossibile leggere la configurazione:{}\n \
Controlla il file a riga: {} e colonna:{}").format(e.doc, e.lineno, e.colno))
except IOError as ee:
self.log.error(self.tr("Impossibile aprire il file: {}").format(ee))
except Exception as eee:
self.log.critical(self.tr("Eccezione inaspettata: {}").format(eee))
else:
self.log.error(self.tr("Non ho trovato alcun file di configurazione!"))
pass
def reload(self):
self.settingsList = None
self.fileList = None
self.inUse = None
self.open()
pass
def use(self, toUse):
self.inUse = toUse
return self
def save(self, fName=None):
if fName is None:
fName=self.inUse
self.log.info(self.tr("Salvo la configurazione: {}").format(fName))
try:
f=open(fName, 'w')
json.dump(self.settingsList[self.inUse], f, indent='\t')
f.close()
except IOError as e:
self.log.error(self.tr("Impossibile salvare il file: {} - [{}]").format(fName,e))
except Exception as ei:
self.log.error(self.tr("Errore imprevisto nella scrittura del file: {}").format(ei))
pass
def getFiles(self):
return self.fileList
def getParam(self, *keys):
rv = self.settingsList[self.inUse]
try:
for k in keys:
rv = rv[k]
return rv
except ValueError as ve:
self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve))
return False
pass
def setParam(self, keys=(), val=None):
sv = self.settingsList[self.inUse]
try:
for k in keys[:-1]:
sv = sv[k]
sv[keys[-1]] = val
return True
except ValueError as ve:
self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve))
return False
pass
def dump(self):
return self.settingsList[self.inUse]
def loads(self, conf):
jconf = json.loads(conf)
self.settingsList[self.inUse]=jconf
def open(self):
self.log.info(self.tr("Carico i file di configurazione"))
self.fileList = glob.glob(r"*.json")
if len(self.fileList) > 0:
for f in self.fileList:
try:
fp = open(f)
tf = json.load(fp)
fName = f.split("\\")[-1]
self.settingsList[fName] = copy.deepcopy(tf)
self.log.info(self.tr("Caricato correttamente: {}").format(fName))
fp.close()
except json.JSONDecodeError as e:
self.log.error(self.tr("Impossibile leggere la configurazione:{}\n \
Controlla il file a riga: {} e colonna:{}").format(e.doc, e.lineno, e.colno))
except IOError as ee:
self.log.error(self.tr("Impossibile aprire il file: {}").format(ee))
except Exception as eee:
self.log.critical(self.tr("Eccezione inaspettata: {}").format(eee))
else:
self.log.error(self.tr("Non ho trovato alcun file di configurazione!"))
pass
def reload(self):
self.settingsList = None
self.fileList = None
self.inUse = None
self.open()
pass
def use(self, toUse):
self.inUse = toUse
return self
def save(self, fName=None):
if fName is None:
fName=self.inUse
self.log.info(self.tr("Salvo la configurazione: {}").format(fName))
try:
f=open(fName, 'w')
json.dump(self.settingsList[self.inUse], f, indent='\t')
f.close()
except IOError as e:
self.log.error(self.tr("Impossibile salvare il file: {} - [{}]").format(fName,e))
except Exception as ei:
self.log.error(self.tr("Errore imprevisto nella scrittura del file: {}").format(ei))
pass
def getFiles(self):
return self.fileList
def getParam(self, *keys):
rv = self.settingsList[self.inUse]
try:
for k in keys:
rv = rv[k]
return rv
except ValueError as ve:
self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve))
return False
pass
def setParam(self, keys=(), val=None):
sv = self.settingsList[self.inUse]
try:
for k in keys[:-1]:
sv = sv[k]
sv[keys[-1]] = val
return True
except ValueError as ve:
self.log.error(self.tr("Parametro di configurazione non valido! [{}]").format(ve))
return False
pass
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
class fancyLogger(QObject):
'''
Colorizza il logger di python, per un' esperienza stile willy wonka
'''
sendLog = pyqtSignal(str)
def __init__(self, filepath=None, name="Logger", consoleLog=True, fileLog=False):
QObject.__init__(self)
try:
with open(filepath, 'r') as fp:
settings = json.load(fp)
fp.close()
colorama.init(convert=True)
self.LRED = colorama.Fore.LIGHTRED_EX
self.RED = colorama.Fore.RED
self.LYELLOW = colorama.Fore.LIGHTYELLOW_EX
self.YELLOW = colorama.Fore.YELLOW
self.LBLUE = colorama.Fore.LIGHTBLUE_EX
self.BLUE = colorama.Fore.BLUE
self.LGREEN = colorama.Fore.LIGHTGREEN_EX
self.LGREEN = colorama.Fore.GREEN
self.WHITE = colorama.Fore.LIGHTWHITE_EX
self.RST = colorama.Style.RESET_ALL
# Setup Logger
self.LOGGER = logging.getLogger(name)
self.LOGGER.setLevel(logging.DEBUG)
self.LOGGER.propagate = False
FORMATTER = logging.Formatter((settings["logFormat"]), (settings["logTimeFormat"]))
if fileLog:
# File Logging
fh = logging.FileHandler((settings["logFile"]))
fh.setLevel(logging.DEBUG)
fh.setFormatter(FORMATTER)
self.LOGGER.addHandler(fh)
if consoleLog:
# Console Logging
cl= logging.StreamHandler(sys.stdout)
cl.setLevel(logging.DEBUG)
cl.setFormatter(FORMATTER)
self.LOGGER.addHandler(cl)
except IOError as e:
print("Impossibile caricare la configurazione del logger: [{}]".format(e))
except Exception as ee:
print(f"libFancylogger error: {ee}")
pass
def debug(self, msg="Undefined Debug"):
print(self.LBLUE, end='')
self.LOGGER.debug(msg)
print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#03c2fc'>DEBUG | {msg} </br>")
pass
def info(self, msg="Undefined Info"):
print(self.LGREEN, end='')
self.LOGGER.info(msg)
print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#6bfc03'>INFO | {msg} </br>")
pass
def warn(self, msg="Undefined Warning"):
print(self.LYELLOW, end='')
self.LOGGER.warning(msg)
print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#fc9403'>WARNING | {msg} </br>")
pass
def error(self, msg="Undefined Error"):
print(self.LRED, end='')
self.LOGGER.error(msg)
print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#ff0000'>ERROR | {msg} </br>")
pass
def critical(self, msg="Undefined Critical"):
print(self.RED, end='')
self.LOGGER.critical(msg)
print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#fc03ce'>CRITICAL | {msg} </br>")
pass
def testColors(self):
self.debug("Test Debug")
self.info("Test Info")
self.warn("Test Warning")
self.error("Test Error")
self.critical("Test Critical")
pass
'''
Colorizza il logger di python, per un' esperienza stile willy wonka
'''
sendLog = pyqtSignal(str)
def __init__(self, filepath=None, name="Logger", consoleLog=True, fileLog=False):
QObject.__init__(self)
try:
with open(filepath, 'r') as fp:
settings = json.load(fp)
fp.close()
colorama.init(convert=True)
self.LRED = colorama.Fore.LIGHTRED_EX
self.RED = colorama.Fore.RED
self.LYELLOW = colorama.Fore.LIGHTYELLOW_EX
self.YELLOW = colorama.Fore.YELLOW
self.LBLUE = colorama.Fore.LIGHTBLUE_EX
self.BLUE = colorama.Fore.BLUE
self.LGREEN = colorama.Fore.LIGHTGREEN_EX
self.LGREEN = colorama.Fore.GREEN
self.WHITE = colorama.Fore.LIGHTWHITE_EX
self.RST = colorama.Style.RESET_ALL
# Setup Logger
self.LOGGER = logging.getLogger(name)
self.LOGGER.setLevel(logging.DEBUG)
self.LOGGER.propagate = False
FORMATTER = logging.Formatter((settings["logFormat"]), (settings["logTimeFormat"]))
if fileLog:
# File Logging
fh = logging.FileHandler((settings["logFile"]))
fh.setLevel(logging.DEBUG)
fh.setFormatter(FORMATTER)
self.LOGGER.addHandler(fh)
if consoleLog:
# Console Logging
cl= logging.StreamHandler(sys.stdout)
cl.setLevel(logging.DEBUG)
cl.setFormatter(FORMATTER)
self.LOGGER.addHandler(cl)
except IOError as e:
print("Impossibile caricare la configurazione del logger: [{}]".format(e))
except Exception as ee:
print(f"libFancylogger error: {ee}")
pass
def debug(self, msg="Undefined Debug"):
print(self.LBLUE, end='')
self.LOGGER.debug(msg)
print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#03c2fc'>DEBUG | {msg} </br>")
pass
def info(self, msg="Undefined Info"):
print(self.LGREEN, end='')
self.LOGGER.info(msg)
print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#6bfc03'>INFO | {msg} </br>")
pass
def warn(self, msg="Undefined Warning"):
print(self.LYELLOW, end='')
self.LOGGER.warning(msg)
print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#fc9403'>WARNING | {msg} </br>")
pass
def error(self, msg="Undefined Error"):
print(self.LRED, end='')
self.LOGGER.error(msg)
print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#ff0000'>ERROR | {msg} </br>")
pass
def critical(self, msg="Undefined Critical"):
print(self.RED, end='')
self.LOGGER.critical(msg)
print(self.RST, end='')
self.sendLog.emit(f"<FONT COLOR='#fc03ce'>CRITICAL | {msg} </br>")
pass
def testColors(self):
self.debug("Test Debug")
self.info("Test Info")
self.warn("Test Warning")
self.error("Test Error")
self.critical("Test Critical")
pass

View File

@@ -10,397 +10,395 @@ import time, parse, re, copy, os, json
import traceback
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
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()
if self.settings['removeDuplicates']:
self.log.info(self.tr("Controllo se ci sono dei duplicati.."))
self.removeDuplicates()
else:
for idx, ff in enumerate(self.contentList):
ff['duplicate']=False
self.contentList[idx]=ff
self.log.warn(self.tr("Salto il controllo dei duplicati.."))
# se il parse e la rimozione dei duplicati e' andata bene
# preparo e inizio il salvataggio
if os.path.exists(self.outPath):
if self.settings['removeOldFiles']:
#os.chdir(self.outPath)
for f in os.listdir(self.outPath):
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:
self.log.critical(self.tr("Il file [{}] contiene caratteri non compatibili con la codifica scelta! [{}]")
.format(self.fileParams['name'],ee))
except FileExistsError as fe:
self.log.critical(fe)
except Exception as ee:
traceback.print_exc()
self.log.warn(ee)
pass
def openFile(self):
try:
#os.chdir(self.paths["INworkPath"])
self.log.info(self.tr("Carico il contenuto.."))
fp = open(self.paths["INworkPath"]+'/'+self.fileParams['name'], mode='r', encoding=self.settings['encoding'])
self.rawFile = fp.readlines()
fp.close()
except IOError as e:
self.log.critical(self.tr("Impossibile aprire il file: {}! [{}]").format(self.fileName,e))
raise BaseException("OpenFile")
os.rmdir(self.outPath)
except Exception as ee:
print(ee)
pass
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
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()
if self.settings['removeDuplicates']:
self.log.info(self.tr("Controllo se ci sono dei duplicati.."))
self.removeDuplicates()
else:
for idx, ff in enumerate(self.contentList):
ff['duplicate']=False
self.contentList[idx]=ff
self.log.warn(self.tr("Salto il controllo dei duplicati.."))
# se il parse e la rimozione dei duplicati e' andata bene
# preparo e inizio il salvataggio
if os.path.exists(self.outPath):
if self.settings['removeOldFiles']:
#os.chdir(self.outPath)
for f in os.listdir(self.outPath):
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:
self.log.critical(self.tr("Il file [{}] contiene caratteri non compatibili con la codifica scelta! [{}]")
.format(self.fileParams['name'],ee))
except FileExistsError as fe:
self.log.critical(fe)
except Exception as ee:
traceback.print_exc()
self.log.warn(ee)
pass
def openFile(self):
try:
#os.chdir(self.paths["INworkPath"])
self.log.info(self.tr("Carico il contenuto.."))
fp = open(self.paths["INworkPath"]+'/'+self.fileParams['name'], mode='r', encoding=self.settings['encoding'])
self.rawFile = fp.readlines()
fp.close()
except IOError as e:
self.log.critical(self.tr("Impossibile aprire il file: {}! [{}]").format(self.fileName,e))
raise BaseException("OpenFile")
os.rmdir(self.outPath)
except Exception as ee:
print(ee)
pass
def remEmptyLines(self):
self.log.info(self.tr("Elimino righe vuote e caratteri inutili.."))
tempContent = []
try:
for ll in self.rawFile:
for c in self.settings['delChars']:
ll = ll.replace(c,'')
if ll not in ['\n', '\r', '\r\n']:
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 remEmptyLines(self):
self.log.info(self.tr("Elimino righe vuote e caratteri inutili.."))
tempContent = []
try:
for ll in self.rawFile:
for c in self.settings['delChars']:
ll = ll.replace(c,'')
if ll not in ['\n', '\r', '\r\n']:
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 newSplitFile(self): #porting del codice dal programma originale
self.log.info(self.tr("Individuo il contenuto.."))
self.bodyCounter=0
self.duplicateNumber=0
docNumber = 0
docSkipped = 0
docDate = {}
title = ''
prevLine = ''
newsPaperName = ''
titleBegin = True
newsName = False
tempBody = list()
for l in self.rawFile: #per ogni linea del file
l=l.replace('\xa0', ' ')
lineWords = l.lstrip().split(' ') #dividi la riga in parole
if self.status == 'first':
try:
# ricerco la data
if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']:
try:
docDate=parse.parse(self.docStruct['dateFormat'],l).named
docDate['month']=docDate['month'].lstrip().rstrip().capitalize()
docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1
# dopo la data inizia il titolo, ma prima si cerca il nome del giornale
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].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
elif self.status == 'tail':
if anomaly or (re.match(self.docStruct['endOfDocument'],l) is not None):
self.status = 'first'
anomaly = False
titleBegin = True
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
self.log.info(self.tr("Individuo il contenuto.."))
self.bodyCounter=0
self.duplicateNumber=0
docNumber = 0
docSkipped = 0
docDate = {}
title = ''
prevLine = ''
newsPaperName = ''
titleBegin = False
tempBody = list()
docSep=re.compile(self.docStruct['docSep'])
for l in self.rawFile: #per ogni linea del file
lineWords = l.lstrip().split(' ') #dividi la riga in parole
if self.status == 'first':
#prendo il numero di documento per vedere se ci sono buchi
try:
try:
nn = parse.parse("{current:d} Of {total} Documents",l.strip().capitalize()).named
if nn["current"]-docNumber==1:
pass
else:
if self.settings["showSkipped"]:
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"]))
docSkipped+=1
docNumber = nn["current"]
except:
pass #non segnalare eccezione se il parse fallisce
# ricerco la data
if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']:
try:
docDate=parse.parse(self.docStruct['dateFormat'],l).named
docDate['month']=docDate['month'].lstrip().rstrip().capitalize()
docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1
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 newSplitFile(self): #porting del codice dal programma originale
self.log.info(self.tr("Individuo il contenuto.."))
self.bodyCounter=0
self.duplicateNumber=0
docNumber = 0
docSkipped = 0
docDate = {}
title = ''
prevLine = ''
newsPaperName = ''
titleBegin = True
newsName = False
tempBody = list()
for l in self.rawFile: #per ogni linea del file
l=l.replace('\xa0', ' ')
lineWords = l.lstrip().split(' ') #dividi la riga in parole
if self.status == 'first':
try:
# ricerco la data
if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']:
try:
docDate=parse.parse(self.docStruct['dateFormat'],l).named
docDate['month']=docDate['month'].lstrip().rstrip().capitalize()
docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1
# dopo la data inizia il titolo, ma prima si cerca il nome del giornale
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].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
elif self.status == 'tail':
if anomaly or (re.match(self.docStruct['endOfDocument'],l) is not None):
self.status = 'first'
anomaly = False
titleBegin = True
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
self.log.info(self.tr("Individuo il contenuto.."))
self.bodyCounter=0
self.duplicateNumber=0
docNumber = 0
docSkipped = 0
docDate = {}
title = ''
prevLine = ''
newsPaperName = ''
titleBegin = False
tempBody = list()
docSep=re.compile(self.docStruct['docSep'])
for l in self.rawFile: #per ogni linea del file
lineWords = l.lstrip().split(' ') #dividi la riga in parole
if self.status == 'first':
#prendo il numero di documento per vedere se ci sono buchi
try:
try:
nn = parse.parse("{current:d} Of {total} Documents",l.strip().capitalize()).named
if nn["current"]-docNumber==1:
pass
else:
if self.settings["showSkipped"]:
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"]))
docSkipped+=1
docNumber = nn["current"]
except:
pass #non segnalare eccezione se il parse fallisce
# ricerco la data
if (lineWords[self.settings['monthPosition']]).capitalize() in self.docStruct['language']['dateWords']:
try:
docDate=parse.parse(self.docStruct['dateFormat'],l).named
docDate['month']=docDate['month'].lstrip().rstrip().capitalize()
docDate['month']=self.docStruct['language']['dateWords'].index(docDate['month'])+1
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 removeDuplicates(self):
titleList=[]
duplicateList=[]
for idx, ff in enumerate(self.contentList):
if ff['title'] not in titleList:
titleList.append(ff['title'])
ff['duplicate']=False
self.contentList[idx]=ff
pass
else:
if ff['title'] not in duplicateList:
duplicateList.append(ff['title'])
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
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
def removeDuplicates(self):
titleList=[]
duplicateList=[]
for idx, ff in enumerate(self.contentList):
if ff['title'] not in titleList:
titleList.append(ff['title'])
ff['duplicate']=False
self.contentList[idx]=ff
pass
else:
if ff['title'] not in duplicateList:
duplicateList.append(ff['title'])
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
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