vendredi 7 février 2020

Python script to generate random names using sampling reservoir : write to a csv file and class issue

I am quit new (big beginner to be honest) to Python and trying to create a random username generator.

The goal of my project is to :

  1. import a sample dataset from a csv file containing the first and last names of people separated by tab in an alphabetical order.
  2. generate an output csv file which would append first name from a random row to a last name from an other row.

The user should be able to select how many username he wants to generate (such as " I want to create 100K+ users randomly and write it to the file 'username.csv')

The output file I am looking for to generate should look like something such as this :

Nikolas Abishek 
Benjamin Franklin
...

I have come up with this code after some research :

import csv

name = open ('../data/original/names.csv')
username = open ('../data/original/usernames.csv' , "w")

numberofuser = int(input('How many users do you want to generate ? '))
readnames = csv.reader(name, delimiter = '\t')
counter = 0
while counter < numberofuser:
    for index,row in enumerate(readnames):
        if index == 0:
                chosen_row = row
                username.write(row)
        else:
            r = random.randint(0, index)
            username.write(row)
            if r == 0 :
                    chosen_row = row
                    username.write(row)
    counter = counter + 1
print ("" + str(numberofuser) + " users has been generated")

Looking at this article about reservoir sampling, I had this idea to implement it. My error message is as follow :

    ➜  lib git:(master) ✗ python genname.py
How many users do you want to generate ? 5
Traceback (most recent call last):
  File "genname.py", line 13, in <module>
    username.write(row)
TypeError: write() argument must be str, not list

So I understand that the problem is that the write(row) can't take a list as an argument. But I can't manage to find how to separate the list to write each element of it to a new row in my output file. Do you have any idea on how to do this ?

This is my first stackoverflow message, I hope my question is clear.

Thank you for reading.

J.




Aucun commentaire:

Enregistrer un commentaire