majles_codes_update

This commit is contained in:
hsafaei
2025-11-06 11:41:24 +03:30
parent 498c3c4bd1
commit aa47259860
10 changed files with 1569 additions and 476 deletions
+366 -15
View File
@@ -6,12 +6,34 @@ from time import sleep
from elasticsearch import Elasticsearch,helpers
class ElasticHelper():
# ----------------------------start---------------------------
# کلاس ElasticHelper:
# نوع ورودی: بدون ورودی مستقیم در تعریف کلاس
# نوع خروجی: شیء از نوع ElasticHelper
# عملیات:
# - متغیرهای کلاسی برای شمارش و مدیریت عملیات تعریف می‌کند
# - مسیر پیش‌فرض مپینگ‌ها را تنظیم می‌کند
# -----------------------------end----------------------------
counter = 0
total = 0
id = ""
path_mappings = os.getcwd() + '/repo/_other/'
# ----------------------------start---------------------------
# متد __init__:
# نوع ورودی:
# - es_url: آدرس Elasticsearch (str) - پیش‌فرض "http://127.0.0.1:6900"
# - es_pass: رمز عبور (str) - پیش‌فرض خالی
# - es_user: نام کاربری (str) - پیش‌فرض "elastic"
# - path_mappings: مسیر مپینگ‌ها (str) - پیش‌فرض خالی
# نوع خروجی: شیء ElasticHelper
# عملیات:
# - اتصال به Elasticsearch را برقرار می‌کند
# - در صورت وجود رمز عبور، از احراز هویت استفاده می‌کند
# - تا 10 بار برای اتصال مجدد تلاش می‌کند (هر بار 5 ثانیه انتظار)
# - در صورت عدم موفقیت، پیام خطا نمایش داده می‌شود
# -----------------------------end----------------------------
def __init__(self, es_url="http://127.0.0.1:6900", es_pass="", es_user="elastic", path_mappings = ""):
if path_mappings :
@@ -25,8 +47,8 @@ class ElasticHelper():
http_auth=(es_user, es_pass),
)
print(es_url)
print(self.es)
# print(es_url)
# print(self.es)
self.success_connect = False
for a in range(0,10):
@@ -50,7 +72,13 @@ class ElasticHelper():
self.total = 0
self.id = ""
def search(self, **params):
try:
res = self.es.search(**params)
except:
return {'hits':{'hits':[]}}
return res
def get_doctument(self, index_name, id):
res = self.es.get(index=index_name, id=id)
return res
@@ -59,6 +87,19 @@ class ElasticHelper():
res = self.es.exists(index=index_name, id=id)
return res
# ----------------------------start---------------------------
# متد update_index_doc:
# نوع ورودی:
# - is_update_state: تعیین عملیات (update یا index) (bool)
# - index_name_o: نام اندیس (str)
# - eid: شناسه سند (str)
# - data: داده‌های سند (dict)
# نوع خروجی: پاسخ Elasticsearch (dict)
# عملیات:
# - اگر is_update_state=True باشد: سند را آپدیت می‌کند
# - در غیر این صورت: سند جدید ایجاد می‌کند
# -----------------------------end----------------------------
def update_index_doc(self, is_update_state, index_name_o, eid, data):
if is_update_state:
resp = self.es.update(index=index_name_o, id=eid, doc=data)
@@ -68,6 +109,21 @@ class ElasticHelper():
return resp
# ----------------------------start---------------------------
# متد exportToJsonForAI:
# نوع ورودی:
# - path_back: مسیر ذخیره فایل (str)
# - index_name: نام اندیس (str)
# - out_name: نام فایل خروجی (str) - پیش‌فرض خالی
# - body: بدنه جستجو (dict) - پیش‌فرض خالی
# - fields: لیست فیلدهای مورد نیاز (list) - پیش‌فرض خالی
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - داده‌های اندیس را با استفاده از scroll API دریافت می‌کند
# - پیشرفت عملیات را نمایش می‌دهد
# - داده‌ها را در فایل JSON ذخیره می‌کند
# - اگر fields مشخص شده باشد، فقط فیلدهای مورد نظر را استخراج می‌کند
# -----------------------------end----------------------------
def exportToJsonForAI(self, path_back, index_name, out_name= '', body={}, fields=[], mode='normal', collapse_field = '') :
print('*' * 50, ' start backup -->', index_name)
self.counter = 0
@@ -169,14 +225,33 @@ class ElasticHelper():
##############################
def backupIndexToZipfile(self, path_back, index_name, out_name= '', body={}, byzip = True, fields=[], noFields=[]) :
# ----------------------------start---------------------------
# متد backupIndexToZipfile:
# نوع ورودی:
# - path_back: مسیر ذخیره فایل (str)
# - index_name: نام اندیس (str)
# - out_name: نام فایل خروجی (str) - پیش‌فرض خالی
# - body: بدنه جستجو (dict) - پیش‌فرض {"size":1000}
# - byzip: تعیین فرمت خروجی (bool) - پیش‌فرض True
# - fields: لیست فیلدهای مورد نیاز (list) - پیش‌فرض خالی
# - noFields: لیست فیلدهای مورد حذف (list) - پیش‌فرض خالی
# نوع خروجی: bool (True اگر داده وجود داشته باشد)
# عملیات:
# - داده‌های اندیس را با استفاده از scroll API دریافت می‌کند
# - پیشرفت عملیات را نمایش می‌دهد
# - داده‌ها را در فایل ZIP یا JSON ذخیره می‌کند
# - اگر fields مشخص شده باشد، فقط فیلدهای مورد نظر را استخراج می‌کند
# - اگر noFields مشخص شده باشد، فیلدهای مورد نظر را حذف می‌کند
# -----------------------------end----------------------------
def backupIndexToZipfile(self, path_back, index_name, file_name= '', body={"size":1000}, byzip = True, fields=[], noFields=[]) :
print('*' * 50, ' start backup -->', index_name)
self.counter = 0
sid = None
out = out_name
if out_name == '' :
out = index_name
out = index_name
if file_name == '' :
file_name = index_name
if body == {} :
@@ -189,19 +264,17 @@ class ElasticHelper():
s_res = self.es.search(
index=index_name,
scroll='5m',
size=1000,
body=body
)
self.total = s_res["hits"]["total"]['value']
if self.total == 0 :
print('total index_name by query = %d' % self.total)
return False
if byzip:
fout = zipfile.ZipFile(path_back + "/"+ out + '.zip', 'w')
fout = zipfile.ZipFile(path_back + "/"+ file_name + '.zip', 'w')
else:
fout = open( path_back + "/"+ out + '.json', 'a+' , encoding='utf-8')
fout = open( path_back + "/"+ file_name + '.json', 'a+' , encoding='utf-8')
print('start index = %s' % index_name)
@@ -210,10 +283,14 @@ class ElasticHelper():
sid = s_res['_scroll_id']
scroll_size = len(s_res['hits']['hits'])
file_count = 1
prev_percent = 0
while scroll_size > 0:
"Scrolling..."
self.counter += scroll_size
print("progress -> %.2f %%" % ((self.counter / self.total)*100))
percent = int((self.counter / self.total)*100)
if percent != prev_percent :
print("progress -> %.2f %%" % percent)
prev_percent = percent
#############################
out_json = []
for item in s_res['hits']['hits']:
@@ -253,6 +330,21 @@ class ElasticHelper():
fout.close()
# ----------------------------start---------------------------
# متد restorFileToElastic:
# نوع ورودی:
# - path_back: مسیر فایل (str)
# - index_name: نام اندیس (str)
# - app_key: کلید برنامه برای مپینگ (str) - پیش‌فرض خالی
# - queryDelete: تعیین حذف اندیس قبل از بازیابی (bool) - پیش‌فرض True
# - map_name: نام فایل مپینگ (str) - پیش‌فرض خالی
# نوع خروجی: bool
# عملیات:
# - وجود فایل ZIP را بررسی می‌کند
# - اگر queryDelete=True باشد، از کاربر تأیید حذف را می‌گیرد
# - اندیس را ایجاد می‌کند
# - داده‌ها را از فایل ZIP به Elasticsearch بازیابی می‌کند
# -----------------------------end----------------------------
def restorFileToElastic(self, path_back, index_name, app_key = '', queryDelete = True, map_name='') :
if not os.path.exists(path_back) :
print(' **** error *** path not exist: ', path_back)
@@ -290,6 +382,19 @@ class ElasticHelper():
self.zipFileToElastic(file_path, index_name)
# ----------------------------start---------------------------
# متد renameElasticIndex:
# نوع ورودی:
# - index_name_i: نام اندیس منبع (str)
# - index_name_o: نام اندیس مقصد (str)
# - app_key: کلید برنامه برای مپینگ (str) - پیش‌فرض خالی
# - map_name: نام فایل مپینگ (str) - پیش‌فرض خالی
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - اندیس مقصد را ایجاد می‌کند
# - با استفاده از reindex API، داده‌ها را از اندیس منبع به مقصد منتقل می‌کند
# - پیشرفت عملیات را نمایش می‌دهد
# -----------------------------end----------------------------
def renameElasticIndex(self, index_name_i, index_name_o, app_key = '', map_name='') :
if self.createIndex(index_name_o, app_key, map_name) :
@@ -317,6 +422,16 @@ class ElasticHelper():
print( '----', index_name_o, ' complated')
# ----------------------------start---------------------------
# متد deleteIndex:
# نوع ورودی:
# - index_name: نام اندیس (str)
# نوع خروجی: bool
# عملیات:
# - وجود اندیس را بررسی می‌کند
# - از کاربر تأیید حذف را می‌گیرد
# - در صورت تأیید، اندیس را حذف می‌کند
# -----------------------------end----------------------------
def deleteIndex(self, index_name) :
if not self.es.indices.exists(index=index_name) :
print(' ' * 10, " for delete NOT exist index :", index_name )
@@ -330,6 +445,17 @@ class ElasticHelper():
else :
return False
# ----------------------------start---------------------------
# متد query_yes_no:
# نوع ورودی:
# - question: سوال نمایش داده شده (str)
# - default: پاسخ پیش‌فرض (str) - پیش‌فرض "no"
# نوع خروجی: bool
# عملیات:
# - سوال را به کاربر نمایش می‌دهد
# - پاسخ کاربر را دریافت و اعتبارسنجی می‌کند
# - True برای 'yes'/'y' و False برای 'no'/'n' برمی‌گرداند
# -----------------------------end----------------------------
def query_yes_no(self, question, default="no"):
valid = { "yes": True, "y": True, "ye": True, "no": False, "n": False }
if default is None:
@@ -352,6 +478,16 @@ class ElasticHelper():
else:
sys.stdout.write("لطفا یکی از موارد روبرو را وارد کنید : 'yes' or 'no' " "(or 'y' or 'n').\n")
# ----------------------------start---------------------------
# متد createIndexIfNotExist:
# نوع ورودی:
# - index_name_o: نام اندیس (str)
# - mapping_o: مپینگ اندیس (str) - پیش‌فرض خالی
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - وجود اندیس را بررسی می‌کند
# - در صورت عدم وجود، اندیس را با مپینگ مشخص شده ایجاد می‌کند
# -----------------------------end----------------------------
def createIndexIfNotExist(self, index_name_o, mapping_o=""):
try:
if not self.es.indices.exists(index=index_name_o):
@@ -362,6 +498,19 @@ class ElasticHelper():
print("....... index exist ! ... not created")
# ----------------------------start---------------------------
# متد createIndex:
# نوع ورودی:
# - index_name: نام اندیس (str)
# - app_key: کلید برنامه برای مپینگ (str) - پیش‌فرض خالی
# - map_name: نام فایل مپینگ (str) - پیش‌فرض خالی
# نوع خروجی: bool
# عملیات:
# - وجود اندیس را بررسی می‌کند
# - مسیر فایل مپینگ را تعیین می‌کند
# - فایل مپینگ را خوانده و اندیس را ایجاد می‌کند
# - در صورت عدم یافت فایل مپینگ، خطا نمایش داده می‌شود
# -----------------------------end----------------------------
def createIndex(self, index_name, app_key='', map_name=''):
path_base = self.path_mappings
@@ -408,8 +557,18 @@ class ElasticHelper():
return False
# ----------------------------start---------------------------
# متد updateBulkList:
# نوع ورودی:
# - listData: لیست داده‌ها (list)
# - index_name: نام اندیس (str)
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - داده‌ها را به صورت bulk آپدیت می‌کند
# - از helpers.bulk Elasticsearch استفاده می‌کند
# -----------------------------end----------------------------
def updateBulkList(self, listData, index_name):
chunk_size=1000
chunk_size=100000
raise_on_error=False
raise_on_exception=False
stats_only=True
@@ -426,6 +585,16 @@ class ElasticHelper():
)
helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok )
# ----------------------------start---------------------------
# متد importBulkList:
# نوع ورودی:
# - listData: لیست داده‌ها (list)
# - index_name: نام اندیس (str)
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - داده‌ها را به صورت bulk وارد می‌کند
# - از helpers.bulk Elasticsearch استفاده می‌کند
# -----------------------------end----------------------------
def importBulkList(self, listData, index_name):
chunk_size=100000
raise_on_error=False
@@ -444,8 +613,18 @@ class ElasticHelper():
helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok )
# ----------------------------start---------------------------
# متد importJsonDataToElastic:
# نوع ورودی:
# - jsonData: داده‌های JSON (list)
# - index_name: نام اندیس (str)
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - داده‌ها را به صورت bulk وارد می‌کند
# - از helpers.bulk Elasticsearch استفاده می‌کند
# -----------------------------end----------------------------
def importJsonDataToElastic(self, jsonData, index_name, fields=[]):
chunk_size=1000
chunk_size=100000
raise_on_error=False
raise_on_exception=False
stats_only=True
@@ -472,6 +651,18 @@ class ElasticHelper():
helpers.bulk(self.es, actions, chunk_size, raise_on_error, raise_on_exception, stats_only, yield_ok )
# ----------------------------start---------------------------
# متد fileToElastic:
# نوع ورودی:
# - file_path: مسیر فایل (str)
# - index_name: نام اندیس (str)
# - limit_pack: محدودیت تعداد بسته‌ها (int) - پیش‌فرض -1
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - فایل JSON را خوانده و داده‌ها را به Elasticsearch وارد می‌کند
# - اندیس را refresh می‌کند
# - تعداد اسناد را نمایش می‌دهد
# -----------------------------end----------------------------
def fileToElastic(self, file_path, index_name, limit_pack = -1, fields=[]):
if not os.path.exists(file_path):
print("file zip:" , file_path , " not exist")
@@ -485,6 +676,19 @@ class ElasticHelper():
self.es.indices.refresh(index=index_name)
print(self.es.cat.count(index=index_name, format="json"))
# ----------------------------start---------------------------
# متد zipFileToElastic:
# نوع ورودی:
# - file_path: مسیر فایل ZIP (str)
# - index_name: نام اندیس (str)
# - limit_pack: محدودیت تعداد فایل‌ها (int) - پیش‌فرض -1
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - فایل ZIP را باز کرده و هر فایل JSON داخل آن را پردازش می‌کند
# - داده‌ها را به Elasticsearch وارد می‌کند
# - اندیس را refresh می‌کند
# - تعداد اسناد را نمایش می‌دهد
# -----------------------------end----------------------------
def zipFileToElastic(self, file_path, index_name, limit_pack = -1, fields=[]):
if not os.path.exists(file_path):
print("file zip:" , file_path , " not exist for imort to elastic : ", index_name )
@@ -514,6 +718,18 @@ class ElasticHelper():
print(" END Of Import to elastic ", index_name ,"\n")
# ----------------------------start---------------------------
# متد iterateJsonFile:
# نوع ورودی:
# - file_path: مسیر فایل (str)
# - isZip: تعیین نوع فایل (ZIP یا JSON) (bool) - پیش‌فرض True
# - limit_pack: محدودیت تعداد فایل‌ها (int) - پیش‌فرض -1
# نوع خروجی: ژنراتور
# عملیات:
# - اگر isZip=True باشد: فایل ZIP را پردازش می‌کند
# - اگر isZip=False باشد: فایل JSON را پردازش می‌کند
# - داده‌ها را به صورت ژنراتور برمی‌گرداند
# -----------------------------end----------------------------
def iterateJsonFile(self, file_path, isZip=True, limit_pack = -1):
if not os.path.exists(file_path):
print("file zip:" , file_path , " not exist iterateJsonFile " )
@@ -549,6 +765,20 @@ class ElasticHelper():
yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in data)
# ----------------------------start---------------------------
# متد es_iterate_all_documents:
# نوع ورودی:
# - index: نام اندیس (str)
# - body: بدنه جستجو (dict) - پیش‌فرض خالی
# - pagesize: اندازه صفحه (int) - پیش‌فرض 250
# - scroll_timeout: زمان اسکرول (str) - پیش‌فرض "25m"
# - **kwargs: پارامترهای اضافی
# نوع خروجی: ژنراتور
# عملیات:
# - تمام اسناد اندیس را با استفاده از scroll API دریافت می‌کند
# - پیشرفت عملیات را نمایش می‌دهد
# - داده‌ها را به صورت ژنراتور برمی‌گرداند
# -----------------------------end----------------------------
def es_iterate_all_documents(self, index, body="", pagesize=250, scroll_timeout="25m", **kwargs):
"""
Helper to iterate ALL values from a single index
@@ -600,6 +830,89 @@ class ElasticHelper():
yield from ({"source": hit["_source"], "id": hit["_id"]} for hit in hits)
def removeCustomFileds(self, index_name_i, fields=[], renameFileds={}, body={}, bulk_update_size=200):
try:
_list = []
try:
_list = self.es_iterate_all_documents(index_name_i, body)
except Exception as e:
print(e)
bulk_data = []
count = 0
total_count = 0
for mentry in _list:
count += 1
entry = mentry["source"]
id = mentry["id"]
# print(id)
eid = id
# if (count % 100) == 0 :
# print("%s -> %.2f " % (id , (count / self.total) if self.total > 0 else 0))
data_filled = False
data = entry
for col in fields:
if col in data :
del data[col]
elif '.' in col :
cols = col.split('.')
subsource = entry
for sub in cols :
dCol = subsource.get(sub, None)
if dCol :
subsource = dCol
else :
break
for col in renameFileds.items():
if col in data :
dCol = data[col]
data[renameFileds[col]] = dCol
del data[col]
bulk_data.append({
'_id': eid,
'_source' : data
})
# انتقال دسته جمعی کدها به الاستیک
if len(bulk_data) >= bulk_update_size:
total_count += len(bulk_data)
print('=' * 5, ' update bulk --> ' , 'total='+ str(total_count) , str(count))
self.importBulkList(bulk_data, index_name_i)
bulk_data = []
if len(bulk_data) >= 0:
total_count += len(bulk_data)
print('=' * 5, ' update bulk --> ' , 'total='+ str(total_count) , str(count))
self.importBulkList(bulk_data, index_name_i)
bulk_data = []
except Exception as e:
# print("1111")
print(e)
# save_error(id, e)
# ----------------------------start---------------------------
# متد moveCustomFileds:
# نوع ورودی:
# - index_name_i: نام اندیس منبع (str)
# - index_name_o: نام اندیس مقصد (str)
# - fields: لیست فیلدهای مورد انتقال (list) - پیش‌فرض خالی
# - renameFileds: دیکشنری تغییر نام فیلدها (dict) - پیش‌فرض خالی
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - تمام اسناد اندیس منبع را دریافت می‌کند
# - فیلدهای مشخص شده را استخراج و به اندیس مقصد انتقال می‌دهد
# - اگر renameFileds وجود داشته باشد، نام فیلدها را تغییر می‌دهد
# -----------------------------end----------------------------
def moveCustomFileds(self, index_name_i, index_name_o, fields=[], renameFileds={}):
try:
body = {}
@@ -662,6 +975,15 @@ class ElasticHelper():
# save_error(id, e)
# ----------------------------start---------------------------
# متد mappingIndex:
# نوع ورودی:
# - index_name_i: نام اندیس (str)
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - توضیح می‌دهد که تغییر مپینگ از طریق پایتون امکان‌پذیر نیست
# - باید اندیس جدیدی با مپینگ مطلوب ایجاد و رایندکس شود
# -----------------------------end----------------------------
def mappingIndex(self, index_name_i):
# فقط از طریق کیبانا میشه تغییر مپ داد
@@ -669,6 +991,16 @@ class ElasticHelper():
# باید ایندکس جدیدی با مپ مطلوب ایجاد کرد و رایندکس کرد
pass
# ----------------------------start---------------------------
# متد updateByQueryIndex:
# نوع ورودی:
# - index_name_i: نام اندیس (str)
# - body: بدنه آپدیت (dict)
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - اسناد را با استفاده از update_by_query API آپدیت می‌کند
# - در صورت خطا، پیام خطا نمایش داده می‌شود
# -----------------------------end----------------------------
def updateByQueryIndex(self, index_name_i, body):
## sample
# body = {
@@ -690,6 +1022,16 @@ class ElasticHelper():
# save_error(id, e)
# ----------------------------start---------------------------
# متد deleteByQueryIndex:
# نوع ورودی:
# - index_name_i: نام اندیس (str)
# - body: بدنه حذف (dict)
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - اسناد را با استفاده از delete_by_query API حذف می‌کند
# - در صورت خطا، پیام خطا نمایش داده می‌شود
# -----------------------------end----------------------------
def deleteByQueryIndex(self, index_name_i, body):
## sample
# body = {
@@ -706,6 +1048,16 @@ class ElasticHelper():
print(e)
# save_error(id, e)
# ----------------------------start---------------------------
# متد delete_by_ids:
# نوع ورودی:
# - index_name_i: نام اندیس (str)
# - ids: لیست شناسه‌ها (list)
# نوع خروجی: بدون خروجی مستقیم
# عملیات:
# - اسناد با شناسه‌های مشخص شده را حذف می‌کند
# - در صورت خطا، پیام خطا نمایش داده می‌شود
# -----------------------------end----------------------------
def delete_by_ids(self, index_name_i, ids):
try:
# ids = ['test1', 'test2', 'test3']
@@ -717,4 +1069,3 @@ class ElasticHelper():
except Exception as e:
print(e)
# save_error(id, e)
+7 -3
View File
@@ -935,7 +935,13 @@ def getTitleType(caption: str) -> str:
caption = re.sub(r'\s+', ' ', caption.strip()) # حذف فاصله‌های اضافی
caption = caption.replace('\u200c', ' ') # جایگزینی نیم‌فاصله‌ها با فاصله کامل
if caption.startswith("الحاق ") or caption.startswith("قانون الحاق ") or caption.startswith("قانون الحاقیه "):
if "موافقتنامه" in caption or "موافقت نامه" in caption or "کنوانسیون" in caption or \
"قرارداد بین المللی" in caption or "مقررات بین المللی" in caption or "الحاق دولت" in caption or \
"الحاق ایران" in caption or "قرارداد بین المللی" in caption or \
caption.startswith("قانون عضویت دولت") or caption.startswith("قانون عضویت ایران") or caption.startswith("قانون اجازه عضویت"):
return "موافقتنامه"
elif caption.startswith("الحاق ") or caption.startswith("قانون الحاق ") or caption.startswith("قانون الحاقیه "):
return "الحاقی"
elif re.match(r"^قانون اضافه.*قانون", caption):
return "الحاقی"
@@ -986,8 +992,6 @@ def getTitleType(caption: str) -> str:
elif caption.startswith("قانون موقتی ") or caption.startswith("قانون موقت "):
return "موقتی"
elif "موافقتنامه" in caption or "موافقت نامه" in caption:
return "موافقتنامه"
else:
return "اصلی"
+36 -1
View File
@@ -289,6 +289,32 @@ class TextNormalizer:
text = text.strip("\u200c").strip()
return text
def repair_qanon_html(self, html):
if not html :
return ""
text = html
text = re.sub(r'(\t)+', ' ', text)
text = re.sub(r'( )+', ' ', text)
text = text.replace("\\n", "")
text = text.replace("\\r", "")
text = re.sub(r"(\r\n)+", "", text)
text = text.replace("\r", "")
text = re.sub(r"(\d+?) /(\d+?) /(\d+?)", r"\1/\2/\3", text)
text = re.sub(r"(\d+?)/ (\d+?)/ (\d+?)", r"\1/\2/\3", text)
# جابجا کردن اعداد تاریخ
# text = re.sub(r"(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})", r"\3/\2/\1", text)
text = re.sub(r"(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})", r"\3/\2/\1", text)
return text
def date_correction(self, text):
text = re.sub(r"(\d+?)ر(\d+?)ر(\d+?)", r"\1/\2/\3", text)
@@ -451,6 +477,7 @@ class TextNormalizer:
return text
def full_hamzah_normal(self, text):
text = re.sub(r"ئ|ﺌ|ﺋ", "ی", text)
text = re.sub(r"ؤ|ﺅ", "و", text)
@@ -484,7 +511,7 @@ class TextNormalizer:
# "trimLine": True # حذف فضای خالی اضافی در ابتدا و انتهای متن
# }
# normalizer = TextNormalizer()
normalizer = TextNormalizer()
# text = """
# سلام -- ـ ـ خوبی
# دادی ییی بی داد
@@ -511,3 +538,11 @@ class TextNormalizer:
# # text="46- متون زیر به عنوان تبصره‌ های ( 3 ) و ( 4 ) به ماده (-187-) قانون الحاق می ‌شود:"
# normalized_text = normalizer.normalize_qanon(text)
# print(normalized_text)
# html= ' قانون متمم بودجه سال 1321 كشور مصوب 05/ 09/ 1321 '
# html = '''
# <TD WIDTH=35 STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000; padding: 0in"> <br> 3 </TD> <TD WIDTH=389 STYLE="border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; border-right: 1px solid #000000; padding: 0in"> <br> قانون بودجه كل سال 1316 كشور مصوب 23/ 12/ 1315 </TD>
# '''
# print(html)
# print( normalizer.repair_qanon_html(html) )