اذهب إلى المحتوى
  • 0

تحليل بيانات و عمل تقرير و إرسال إيميل في بايثون

Sami Remili

السؤال

سلام عليكم  يا ريت شرح كود سكريبت بايثون

 

#!/usr/bin/env python3

import json
import locale
import sys
import emails
import os
import reports


def load_data(filename):
  """Loads the contents of filename as a JSON file."""
  with open(filename) as json_file:
    data = json.load(json_file)
  return data


def format_car(car):
  """Given a car dictionary, returns a nicely formatted name."""
  return "{} {} ({})".format(
      car["car_make"], car["car_model"], car["car_year"])

car_sales ={}
def calculate_sales_per_year(car, total_sales):
    if(car["car_year"] in car_sales):
        car_sales[car["car_year"]]=car_sales[car["car_year"]]+total_sales
    else:
        car_sales[car["car_year"]]=total_sales

def returns_most_popular_car_year():
    key=''
    value=0
    for k in car_sales:
        if(car_sales[k]>value):
            key = k
            value = car_sales[k]
    return "The most popular year was "+str(key)+" with "+str(value)+" sales."

def process_data(data):
  """Analyzes the data, looking for maximums.
  Returns a list of lines that summarize the information.
  """
  locale.setlocale(locale.LC_ALL, 'en_US.UTF8')
  max_revenue = {"revenue": 0}
  max_sales = {"total_sales": 0}

  for item in data:
    # Calculate the revenue generated by this model (price * total_sales)
    # We need to convert the price from "$1234.56" to 1234.56
    item_price = locale.atof(item["price"].strip("$"))
    item_revenue = item["total_sales"] * item_price
    if item_revenue > max_revenue["revenue"]:
      item["revenue"] = item_revenue
      max_revenue = item
    # TODO: also handle max sales
    if item["total_sales"] > max_sales["total_sales"]:
      max_sales = item
    # TODO: also handle most popular car_year
    calculate_sales_per_year(item["car"],item["total_sales"])

  summary = [
    "The {} generated the most revenue: ${}".format(
      format_car(max_revenue["car"]), max_revenue["revenue"]),
    "The {} had the most sales: {}".format(
      format_car(max_sales["car"]), max_sales["total_sales"]),
      returns_most_popular_car_year()
 ]

  return summary


def cars_dict_to_table(car_data):
  """Turns the data in car_data into a list of lists."""
  table_data = [["ID", "Car", "Price", "Total Sales"]]
  for item in car_data:
    table_data.append([item["id"], format_car(item["car"]), item["price"], item["total_sales"]])
  return table_data

def pdf_generator(summary,data):
    table_data=cars_dict_to_table(data)
    result=''
    for line in summary:
     result=result+line+'<br/>'
    reports.generate("/tmp/reportCars.pdf", "Sales Summary for last month",result,table_data )


def email_send_report(summary):
    sender = "automation@example.com"
    receiver = "{}@example.com".format(os.environ.get('USER'))
    subject = "Sales summary for last month"
    body = '\n'.join(summary)
    message = emails.generate(sender, receiver, subject, body, "/tmp/reportCars.pdf")
    emails.send(message)

def main(argv):
  """Process the JSON data and generate a full report out of it."""
  data = load_data("/home/student/car_sales.json")
  summary = process_data(data)
  # TODO: turn this into a PDF report
  pdf_generator(summary,data)
  # TODO: send the PDF report as an email attachment
  email_send_report(summary)

if __name__ == "__main__":
 main(sys.argv)

 

تم التعديل في بواسطة Wael Aljamal
توضيح السؤال
رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 1

مرحبا،

سأكتب التعليقات المساعدة ضمن الشيفرة البرمجية:

#!/usr/bin/env python3

import json    # json تضمين مكتبة للتعامل مع ضيغة البيانات
import locale  # إعدادات البيئة المحلية LANG environment variable وإجرائيات مساعدة و اللغة
import sys     # تسمح بالوصول لخصائص ودوال في النظام system-specific parameters and functions
import emails  # مكتبة للتعامل مع البريد الإلكتروني
import os      # مكتبة للتعامل مع نظام التشغيل والوصول للملفات
import reports # مكتبة للتعامل مع التقاير

# قراءة ملف 
def load_data(filename):
  """Loads the contents of filename as a JSON file."""
  # json_file تحميل المف في متحول باسم
  with open(filename) as json_file:
    # قراءة البيانات
    data = json.load(json_file)
  # إرجاع البيانات
  return data

# إجرائية لتصنيف السيارات
def format_car(car):
  """Given a car dictionary, returns a nicely formatted name."""
  # تحويل قاموس يحوي بيانات السيارات لصيغة مرتبة منهم
  return "{} {} ({})".format(
    # الصانع - الموديل - سنة التصنيع
      car["car_make"], car["car_model"], car["car_year"])

# مصفوفة لتجميع بيانات السياراة
car_sales ={}
# حساب المبيعات السنوسة
def calculate_sales_per_year(car, total_sales):
    # إذا كنا قد أضفنا هذه السنة  للمصفوفة نقوم بتجميع تراكمي مع المجموع السابق
    if(car["car_year"] in car_sales):
        car_sales[car["car_year"]]=car_sales[car["car_year"]]+total_sales
    # المجموع الكلي يساوي المجموع الحالي
    else:
        car_sales[car["car_year"]]=total_sales

# سيارة السنة أي الأكثر مبيعا مثلا
def returns_most_popular_car_year():
    # دليل السيارة المطلوبة
    key=''
    # عدد المبيعات
    value=0
    # نبحث عن السيارة الهدف في المصفوفة
    for k in car_sales:
        if(car_sales[k]>value):  # عندما نجد السيارة المطلوبة نخزن الدليل و القيمة
            key = k
            value = car_sales[k]
    # طباعة النتائج
    return "The most popular year was "+str(key)+" with "+str(value)+" sales."

  
# معالجة البيانات
def process_data(data):
  """Analyzes the data, looking for maximums.
  Returns a list of lines that summarize the information.
  """
  # تحليل البيانات للبحث عن أكبر المبيعات و الإعادة على شكل قائمة
  locale.setlocale(locale.LC_ALL, 'en_US.UTF8') # تحديد اللغة
  max_revenue = {"revenue": 0}                  #  تهيئة الإيرادات
  max_sales = {"total_sales": 0}                #  تهيئة الإجمالي

  # price * total_sales حساب الإيرادات بالطريقة التالية
  # وتحويل السعر من نص إلى رقم
  for item in data:
    # Calculate the revenue generated by this model (price * total_sales)
    # We need to convert the price from "$1234.56" to 1234.56
    item_price = locale.atof(item["price"].strip("$"))
    item_revenue = item["total_sales"] * item_price
    # الاحتفاظ بأكبر الإيرادات
    if item_revenue > max_revenue["revenue"]:
      item["revenue"] = item_revenue
      max_revenue = item
    # TODO: also handle max sales
    # الاحتفاظ بأكبر المبيعات
    if item["total_sales"] > max_sales["total_sales"]:
      max_sales = item
    # TODO: also handle most popular car_year
    calculate_sales_per_year(item["car"],item["total_sales"])
  # تشكيل الملخص و التقرير لما سبق
  summary = [
    "The {} generated the most revenue: ${}".format(
      format_car(max_revenue["car"]), max_revenue["revenue"]),
    "The {} had the most sales: {}".format(
      format_car(max_sales["car"]), max_sales["total_sales"]),
      returns_most_popular_car_year()
 ]

  return summary

# "ID", "Car", "Price", "Total Sales" تجميع البيانات في جدول مع الحقول 
def cars_dict_to_table(car_data):
  """Turns the data in car_data into a list of lists."""
  table_data = [["ID", "Car", "Price", "Total Sales"]]
  for item in car_data:
    table_data.append([item["id"], format_car(item["car"]), item["price"], item["total_sales"]])
  return table_data


# pdf تصدير التقرير على شكل ملف 
def pdf_generator(summary,data):
    table_data=cars_dict_to_table(data)  # وضع البيانات في صيغة جدول
    result=''                            # تجميع النتائج
    for line in summary:
     result=result+line+'<br/>'
    reports.generate("/tmp/reportCars.pdf", "Sales Summary for last month",result,table_data )

# إرسال إيميل بالنتائج
def email_send_report(summary):
    sender = "automation@example.com"                          # تحديد المرسل
    receiver = "{}@example.com".format(os.environ.get('USER')) # تحديد المستقبل
    subject = "Sales summary for last month"                   # تحديد الموضوع
    body = '\n'.join(summary)                                  # جسم الايميل
    # تهيئة الايميل مع إضافة المرفقات
    message = emails.generate(sender, receiver, subject, body, "/tmp/reportCars.pdf") 
    # الإرسال
    emails.send(message)

def main(argv):
  """Process the JSON data and generate a full report out of it."""
  data = load_data("/home/student/car_sales.json")  # تحميل الملف
  summary = process_data(data)                      # معالجة البيانات
  # TODO: turn this into a PDF report
  pdf_generator(summary,data)                       # pdf عمل تقرير على شكل 
  # TODO: send the PDF report as an email attachment
  email_send_report(summary)                        # إرسال إيميل بالنتائج

# تشغيل البرنامج
if __name__ == "__main__":
 main(sys.argv)

بالتوفيق

رابط هذا التعليق
شارك على الشبكات الإجتماعية

  • 1

السلام عليكم 

يبدأ الكود من هنا 


def main(argv):
  """Process the JSON data and generate a full report out of it."""
  #قراءة ملف بيانات مبيعات سيارة
  data = load_data("/home/student/car_sales.json") 
  #summary متغير لتنفيذ الامر التالي 
  # process_data(data) امر مسؤل عن تحليل بيانات الملف المرفق بالاعلى
  summary = process_data(data) # مسودة 1
  # TODO: turn this into a PDF report
  # انشاء تقرير من الملفات و من تحليل بالبيانات بالاعلى
  pdf_generator(summary,data) # مسودة 2
  # TODO: send the PDF report as an email attachment
  # ارسال التحليل الى البريد الالكتروني 
  email_send_report(summary) # مسودة 3

if __name__ == "__main__":
 main(sys.argv)

مسودة 1

def process_data(data):
  """Analyzes the data, looking for maximums.
  Returns a list of lines that summarize the information.
  """
  locale.setlocale(locale.LC_ALL, 'en_US.UTF8') # تحليل تشفير النص ليقراء العربية
  max_revenue = {"revenue": 0} # متغير اعلى قيمة
  max_sales = {"total_sales": 0}# متغير اجمالي المبيعات

  for item in data: # مصفوفة قراء البيانات الواردة من ملف json 
    # Calculate the revenue generated by this model (price * total_sales)
    # We need to convert the price from "$1234.56" to 1234.56
    item_price = locale.atof(item["price"].strip("$")) # قراءة الارقام فقط من المبلغ و ازالة علامة العملة
    item_revenue = item["total_sales"] * item_price
    if item_revenue > max_revenue["revenue"]: # تسجيل قيمة اعلى قيمة في المتغير بفحص اذا كانت القيمه اكبر من المسجله او لا 
      item["revenue"] = item_revenue
      max_revenue = item
    # TODO: also handle max sales
    if item["total_sales"] > max_sales["total_sales"]: # حساب عدد مبيعات عنصر لمعرفة اذا كان الاكثر مبيعا او لا 
      max_sales = item
    # TODO: also handle most popular car_year
    calculate_sales_per_year(item["car"],item["total_sales"]) # حساب اجمالي المبيعات 
 # انشاء التقرير 
  summary = [
    "The {} generated the most revenue: ${}".format(
      format_car(max_revenue["car"]), max_revenue["revenue"]),
    "The {} had the most sales: {}".format(
      format_car(max_sales["car"]), max_sales["total_sales"]),
      returns_most_popular_car_year()
 ]

  return summary # اخراج النتيجه 

مسودة 2

#انشاء تقرير pdf من البيانات المرسله من المسوده 1
def pdf_generator(summary,data):
    table_data=cars_dict_to_table(data)
    result=''
    for line in summary:
     result=result+line+'<br/>'
    reports.generate("/tmp/reportCars.pdf", "Sales Summary for last month",result,table_data )

مسودة 3

#ارسال ايميل من البيانات في مسودة 1
def email_send_report(summary):
    sender = "automation@example.com"
    receiver = "{}@example.com".format(os.environ.get('USER'))
    subject = "Sales summary for last month"
    body = '\n'.join(summary)
    message = emails.generate(sender, receiver, subject, body, "/tmp/reportCars.pdf")
    emails.send(message)

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...