SHARE
TWEET

GenRandomMember

deciliter Jun 18th, 2019 111 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sat Jun 15 15:03:24 2019
  4.  
  5. It may be needed to type "pip install Faker" or "conda install Faker" into the
  6. command window prior to running the script
  7.  
  8.  
  9.  
  10. DO NOT IMPORT, This must be run as a __MAIN__ to operrate correctly.
  11.  
  12. This is the first part of the midterm project. This script creates a file of
  13. random values to be used by the database management program that makes up the
  14. second part of the project.
  15.  
  16. The script is run, and can take arguments:
  17.     -no <number of members>   ((default value of 1000))
  18.     -fname <filename>    ((default value of memberdata.csv))
  19. No other arguments or formats can be used.
  20.  
  21. The script uses third parter Faker library as a core develpment for random entries.
  22.  
  23. Main takes the script arguments for number of members and output file.
  24. Since there is no mention in project requirements that this should append to existing data,
  25. and that doesn't seem to fit the scope of the usage, the script only checks its own
  26. generated data and will not append, but overwrite a file it is targeted at.
  27.    
  28.  
  29. As a maximum value of 1,000,000 is a project given, the program will reject a given value
  30. above that maximum and generate nothing, prompting the user to recall the prgram with a valid entry.
  31.  
  32.  
  33. @author: Deciliter
  34. """
  35.  
  36.  
  37. ##default values = 1000 members into memberdata.csv
  38. def main(NumberOfMembers: int = 1000, filename: str = "memberdata.csv"):
  39.     """
  40.     Creates a file filled with randomized entries for usage in testing part two of the midterm project.
  41.     Uses significant use of Faker library for ease of code writing that results in
  42.     realistic looking data entries instead of strings of random letters and numbers.
  43.    
  44.     This is not truly needed, but allows for more realistic, and easier testing if
  45.     the data looks like it should in actual usage. It is hard to parse random strings.
  46.    
  47.     Several of the requirements for data such as dates, names, characters, etc are
  48.     baked into the method of generating them "randomly." As such, most of the values
  49.     are not checked. However, there is technically a chance for the DOB+name to produce
  50.     an exact combo, so this is checked. A fail rejects the whole entry and regenerates
  51.     a replacement without counting that entry.
  52.    
  53.     """
  54.    
  55.     #print("running inside")
  56.     #print(NumberOfMembers)
  57.  
  58.     import csv
  59.     import random
  60.     import datetime
  61.     import re
  62.  
  63.  
  64.     #pip install Faker
  65.     from faker import Faker
  66.     fake = Faker()
  67.    
  68.     #creates main list
  69.     MemberList = []
  70.    
  71.     monthconvert = dict(Jan='January', Feb='February', Mar='March', Apr='April',
  72.                         May='May', Jun='June', Jul='July', Aug='August', Sep='September',
  73.                         Oct='October', Nov='November', Dec='December')
  74.     DATE_re = r"([a-z-A-Z]+) (\d{1}|\d{2}) ([\d]{4})\Z"
  75.    
  76.     #loop generates members and appends valid ones to MemberList
  77.     looper = 0
  78.     while looper < NumberOfMembers:
  79.         Member = [] #list to hold gen member until appended to approved list
  80.        
  81.         MemberNumber = format(looper, "06") #generates the member number, sets format to preceeding zeroes
  82.        
  83.         #generates names at random
  84.         MemFName = fake.first_name()
  85.         MemMName = fake.first_name()
  86.         MemLName = fake.last_name()
  87.        
  88.         #generates random adress
  89.         MemAddress = fake.address()
  90.         MemAddress = MemAddress.replace("\n", ", ") #removes newline standard added in faker with ","
  91.        
  92.         #generates status
  93.         MemStatus = random.choice(["Basic", "Silver", "Gold", "Platinum", "None"])
  94.        
  95.         #gen starting date starting with earliest possible up to today
  96.         jyear= random.randint(1981,datetime.datetime.now().year-1)
  97.         jmon= random.randint(1,12)
  98.         jday= random.randint(1, 28)
  99.         MemJoin = datetime.date(jyear, jmon, jday)
  100.        
  101.         #gen birthdate, set such that member must be 18 years at Join Date
  102.         bdays= random.randint(6588,43920) #6588 is 18 years (+ leap year control) in days 43920 is about 120 years
  103.         MemBirth = MemJoin - datetime.timedelta(days=bdays) #subtract age in days from join date
  104.        
  105.         #generates end date if the member has canceled
  106.         if MemStatus == "None":
  107.             MemEnd = fake.date_between(MemJoin, "today")
  108. #            endshift = datetime.datetime.now()-datetime.datetime(MemJoin.year, MemJoin.month, MemJoin.day)
  109. #            print(MemJoin)
  110. #            print(endshift)
  111. #            timemem = random.randint(0,endshift.days)
  112. #            print(timemem)
  113. #            MemEnd = MemJoin + datetime.timedelta(days=timemem)
  114.         else:
  115.             MemEnd = ""
  116.        
  117.         #generates renewel date - a bit odd to have a renew date for canceled members, but this section
  118.         # is noted as being mandatory, possibly used to send a message to lapsed members as well?
  119.         MemRenew = fake.date_between("today", "+5y")#future date up to 5 years out
  120.        
  121.         #generates phone number with no (000) allowed
  122.         #without a list of rules for phone numbers, no real way to guarantee everything is valid
  123.         #I have instead chosen to make the phone number contain the "XXX-555-XXXX" such that
  124.         #all of these numbers are notably fake numbers (555) prefix.
  125.         phone1 = random.randint(100,999) #no 000 area code allowed, this method gets random numbers but retains format
  126.         phone2 = random.randint(1000,9999) #my father's phone number used to end in 0000, but this retains format
  127.         MemPhone = str(phone1)+"555"+str(phone2)
  128.        
  129.         #generates fake email Unlike the phone numbers, these are all possible
  130.         MemEmail = fake.email()
  131.        
  132.         #generates notes
  133.         MemNote = fake.sentence()
  134.        
  135.         #creating entry basis
  136.         Member.append(MemberNumber)
  137.         Member.append(MemFName)
  138.         Member.append(MemMName)
  139.         Member.append(MemLName)
  140.         MemBirth = MemBirth.strftime('%b %d %Y')
  141.         MemBirth_match = re.search(DATE_re, str(MemBirth))
  142.         MemBirth = monthconvert[MemBirth_match.group(1)] + " " + MemBirth_match.group(2) + " " + MemBirth_match.group(3)
  143.         Member.append(MemBirth)
  144.         Member.append(MemAddress)
  145.         Member.append(MemStatus)
  146.         MemJoin = MemJoin.strftime('%b %d %Y')
  147.         MemJoin_match = re.search(DATE_re, str(MemJoin))
  148.         MemJoin = monthconvert[MemJoin_match.group(1)] + " " + MemJoin_match.group(2) + " " + MemJoin_match.group(3)
  149.         Member.append(MemJoin)
  150.         if MemEnd == "": #if check needed to swap str format since this cell is often empty
  151.             Member.append(MemEnd)
  152.         else:
  153.             MemEnd = MemEnd.strftime('%b %d %Y')
  154.             MemEnd_match = re.search(DATE_re, str(MemEnd))
  155.             MemEnd = monthconvert[MemEnd_match.group(1)] + " " + MemEnd_match.group(2) + " " + MemEnd_match.group(3)
  156.             Member.append(MemEnd)
  157.         MemRenew = MemRenew.strftime('%b %d %Y')
  158.         MemRenew_match = re.search(DATE_re, str(MemRenew))
  159.         MemRenew = monthconvert[MemRenew_match.group(1)] + " " + MemRenew_match.group(2) + " " + MemRenew_match.group(3)
  160.         Member.append(MemRenew)
  161.         Member.append(MemPhone)
  162.         Member.append(MemEmail)
  163.         Member.append(MemNote)
  164.        
  165.         #check that member name/DOB combo is not in use
  166.        
  167.         index = 0
  168.         Check = 0
  169.        
  170.         #loops through existing approved list, checks if member exists
  171.         while index < len(MemberList):
  172.             if Member[1:5] == MemberList[index][1:5]:
  173.                 Check = 1 #if member exists, need to reject gen value
  174.                 break
  175.             index = index+1 #loops through whole list of genned members
  176.                
  177.         #if member Check failed, need to reject gen value
  178.         if Check == 1:
  179.             del Member #rejects member and I hope serves to reduce memory consumption by deletion
  180.             continue #regenerates member, does not increment counter so it never occured
  181.        
  182.         MemberList.append(Member) #appends member to approved list
  183.        
  184.         del Member #deletes temporary member to reduce memory usage
  185.        
  186.         looper = looper+1 #moves on to next member looping until needed number of people are made
  187.        
  188.        
  189.  
  190.     #used in testing DO NOT USE HUGE OUTPUT WITH NO PROMPT
  191. #    i=0
  192. #    while i < len(MemberList):
  193. #        print(MemberList[i])
  194. #        i=i+1
  195.  
  196.    
  197.    
  198.     #write header and append all approved members to output list
  199.     header = ["Mno", "First name", "MI", "Last name", "DoB", "Address", "Status", "msd", "med", "rdate", "Phone", "Email", "Notes"]
  200.     MemberList.insert(0,header)
  201.    
  202.     #open file
  203.     with open(filename,"w") as resultout:
  204.         writeCSV = csv.writer(resultout, lineterminator = '\n')
  205.         writeCSV.writerows(MemberList)
  206.    
  207.     #print(MemberList)
  208.     #testing code
  209. #    i=0
  210. #    while i < len(MemberList):
  211. #        print(MemberList[i])
  212. #        i=i+1
  213.     print(MemberList)
  214.    
  215.     #close file
  216.        
  217.        
  218.        
  219.      
  220. import sys
  221.    
  222. #sys grab arguments
  223.  
  224. arguments = sys.argv
  225. NumberOfMembers=1000
  226. filename = "memberdata.csv"
  227.  
  228. #loops through arguments to pull in values to pass to main()
  229. #I wanted to try using Optparse, but I couldn't get it to work with
  230. #the format given for the flags. This method works and will ignore any
  231. #gibberish entered that isn't flagged
  232. i = 0  
  233. argcheck =0 #error checker
  234. while i < len(arguments)-1:
  235.     if arguments[i] == "-no":
  236. #            print("no found")
  237. #            print(arguments[i+1])
  238.         try:
  239.             NumberOfMembers = int(arguments[i+1])
  240.         except ValueError:
  241.             print("Please ensure that an integer lower than 1,000,000 has been given for number of members")
  242.             argcheck = 1
  243.     if arguments[i] == "-fname":
  244. #            print("-fnamefound")
  245. #            print(arguments[i+1])
  246.         filename = arguments[i+1]
  247.     i=i+1
  248.  
  249.  
  250.  
  251. #check that number of member arguments is not too long
  252.  
  253. if NumberOfMembers > 999999:
  254.     print("Number of Members exceeds maximum value")
  255.     argcheck =1 #prevents running of file
  256.  
  257.  
  258.  
  259. #run main only if everything sent is valid
  260. if __name__ == "__main__" and argcheck == 0:
  261.     main(NumberOfMembers, filename)
  262.    
  263. #main(NumberOfMembers, filename)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top