issue108:c_c
Différences
Ci-dessous, les différences entre deux révisions de la page.
| Prochaine révision | Révision précédente | ||
| issue108:c_c [2016/04/30 18:12] – créée auntiee | issue108:c_c [2016/05/09 12:05] (Version actuelle) – auntiee | ||
|---|---|---|---|
| Ligne 1: | Ligne 1: | ||
| - | A few months ago, I was asked to create a JSON database for integration into an ubuntu phone app. Up until then, I’ve only ever used JSON files, but not created them from real-world data/files. I then set about using Python to list all files that should appear in the app, and creating the relevant JSON data. Since then, I’ve begun a data management and analysis course - where we work with similar JSON files. So for this month’s C&C, I’m going to walk you through how I created a new Python script to create a JSON database of my previous C&C articles. This way, I’ll be able to easily check when I wrote an article, and what the topic was. | + | **A few months ago, I was asked to create a JSON database for integration into an ubuntu phone app. Up until then, I’ve only ever used JSON files, but not created them from real-world data/files. I then set about using Python to list all files that should appear in the app, and creating the relevant JSON data. Since then, I’ve begun a data management and analysis course - where we work with similar JSON files. So for this month’s C&C, I’m going to walk you through how I created a new Python script to create a JSON database of my previous C&C articles. This way, I’ll be able to easily check when I wrote an article, and what the topic was. |
| The Script | The Script | ||
| Ligne 7: | Ligne 7: | ||
| But… I Don’t Have Your Articles! | But… I Don’t Have Your Articles! | ||
| - | This script isn’t intended to be used as-is. You can easily adjust it to generate lists/ | + | This script isn’t intended to be used as-is. You can easily adjust it to generate lists/ |
| - | What Will I Need? | + | Il y a quelques mois, on m'a demandé de créer une base données JSON pour l' |
| + | |||
| + | Le script. | ||
| + | |||
| + | J'ai mis une copie de mon script sur Pastebin : http:// | ||
| + | |||
| + | |||
| + | Mais... je n'ai pas vos articles ! | ||
| + | |||
| + | Le script n'est pas fait pour être utilisé tel quel. Il peut être facilement modifié pour générer une liste/base de données de fichiers à partir de leur nom. C'est ce que je vais traiter dans cet article. | ||
| + | |||
| + | **What Will I Need? | ||
| The scripts are tested in Python 3.5. Older versions of 3 should work without issues - if you’re using Python2, you’ll need to adjust the code according to the error messages you’re given. | The scripts are tested in Python 3.5. Older versions of 3 should work without issues - if you’re using Python2, you’ll need to adjust the code according to the error messages you’re given. | ||
| Ligne 15: | Ligne 26: | ||
| I’ve linked my version of the script with Drive - the CLI tool for managing Google Drive. If you’re not interested in using it, you can safely ignore/ | I’ve linked my version of the script with Drive - the CLI tool for managing Google Drive. If you’re not interested in using it, you can safely ignore/ | ||
| - | Otherwise the rest of the imports are necessary, and standard libraries. | + | Otherwise the rest of the imports are necessary, and standard libraries.** |
| + | |||
| + | De quoi aurai-je besoin ? | ||
| + | |||
| + | Les scripts ont été testés dans Python 3.5. Des versions 3, plus anciennes, devraient fonctionner sans problème. Si vous utilisez Python 2, vous devrez corriger le code en fonction des messages d' | ||
| + | |||
| + | J'ai lié ma version du script avec Drive, l' | ||
| + | |||
| + | Par ailleurs, les autres importations sont nécessaires ainsi que les bibliothèques standards. | ||
| - | What Do I Need To Change? | + | **What Do I Need To Change? |
| These changes are mandatory - and need to be adjusted for your system. Optional changes can be found in the next section. | These changes are mandatory - and need to be adjusted for your system. Optional changes can be found in the next section. | ||
| Ligne 33: | Ligne 53: | ||
| Line 16 contains a dictionary that stores the date of issue 100 (August, 2015). This is important for the calculations in dateFind. The reason it’s not integrated into the function, is so it can be more easily changed. | Line 16 contains a dictionary that stores the date of issue 100 (August, 2015). This is important for the calculations in dateFind. The reason it’s not integrated into the function, is so it can be more easily changed. | ||
| - | Line 17 contains the empty dictionary which is used per entry. It could be integrated into a method, but I left it in to illustrate how it works (and to ensure that there’s a -1 element to delete). | + | Line 17 contains the empty dictionary which is used per entry. It could be integrated into a method, but I left it in to illustrate how it works (and to ensure that there’s a -1 element to delete).** |
| - | How Does It Work? | + | Que dois-je changer ? |
| + | |||
| + | Les changements suivants sont obligatoires et doivent être ajustés à votre système. Les changements optionnels se trouvent dans la section suivante. | ||
| + | |||
| + | Il faudra éditer la ligne 9 : il s'agit du fichier de destination (txtFile) pour la liste temporaire de tous les articles. | ||
| + | |||
| + | Vous devrez également éditer la ligne 13 et modifier la liste pour y indiquer les chemins que vous voulez inclure dans votre base de données. Il s' | ||
| + | |||
| + | Si vous ne séparez pas les informations concernant vos fichiers avec des « - », il faudra modifier la ligne 70. | ||
| + | |||
| + | Que puis-je également changer ? | ||
| + | |||
| + | La ligne 10 donne le chemin du fichier JSON. Il s'agit par défaut de fcm-database.json dans le dossier courant. | ||
| + | |||
| + | La ligne 16 contient un dictionnaire où est stockée la date du numéro 100 (August, 2015 [Ndt : août 2015]). C'est important pour les calculs dans dateFind. On ne l'a pas intégrée dans la fonction pour pouvoir la changer plus facilement. | ||
| + | |||
| + | La ligne 17 contient un dictionnaire vide qui est utilisé pour chaque valeur. Il aurait pu être intégré dans une méthode, mais je l'ai laissé ici pour montrer comment il fonctionne (et m' | ||
| + | |||
| + | **How Does It Work? | ||
| The first 25 lines are mainly variables that need to be set up for later functions. Most should be self-explanatory, | The first 25 lines are mainly variables that need to be set up for later functions. Most should be self-explanatory, | ||
| Ligne 43: | Ligne 81: | ||
| This function was created to calculate the month and year that corresponds to the article. This is important for me, as some topics can be outdated - so if a topic was covered in 2012, it may be time for a refresh. It does so by knowing one date (#100 was for August, 2015), and the difference between the currently processed issue, and issue 100. So issue 98 would be a difference of 2, and 107 would be -7. The difference (times 365/12 - roughly one month) is then subtracted from the date of the startPoint (2015-08), and results in a new year and month. The days shift, but since FCM is a monthly release, it’s unimportant (and even deleted entirely with the strftime function). | This function was created to calculate the month and year that corresponds to the article. This is important for me, as some topics can be outdated - so if a topic was covered in 2012, it may be time for a refresh. It does so by knowing one date (#100 was for August, 2015), and the difference between the currently processed issue, and issue 100. So issue 98 would be a difference of 2, and 107 would be -7. The difference (times 365/12 - roughly one month) is then subtracted from the date of the startPoint (2015-08), and results in a new year and month. The days shift, but since FCM is a monthly release, it’s unimportant (and even deleted entirely with the strftime function). | ||
| - | One could also just multiply 32 by the difference - though having that many extra days for some months may cause more problems. It’s by no means perfect - as it’s cumulative, there may be problems with February issues (for example). | + | One could also just multiply 32 by the difference - though having that many extra days for some months may cause more problems. It’s by no means perfect - as it’s cumulative, there may be problems with February issues (for example).** |
| + | |||
| + | Comment cela fonctionne-t-il ? | ||
| + | |||
| + | Les 25 premières lignes sont essentiellement des déclarations de variables qui ont besoin d' | ||
| + | |||
| + | Fonction : dateFind | ||
| + | |||
| + | Cette fonction a été créée pour calculer le mois et l' | ||
| + | |||
| + | On peut aussi simplement multiplier la différence par 32 - bien qu' | ||
| - | Function: createArticleList | + | **Function: createArticleList |
| This function uses os.listdir, and some regexp/ | This function uses os.listdir, and some regexp/ | ||
| Ligne 53: | Ligne 101: | ||
| Line 57 ensures there are no duplicates - as a Python set can contain only unique values. This essentially drops any duplicate filenames. | Line 57 ensures there are no duplicates - as a Python set can contain only unique values. This essentially drops any duplicate filenames. | ||
| - | The list is then printed into a temporary file (which is practical for debugging, or if you just want to see quickly how many files there are). The file is then closed, and the function returns True. | + | The list is then printed into a temporary file (which is practical for debugging, or if you just want to see quickly how many files there are). The file is then closed, and the function returns True.** |
| - | Function: update_database | + | Fonction : createArticleList |
| + | |||
| + | Cette fonction utilise os.listdir et quelques recherches regexp pour ne tenir compte que de mes articles. Puisque le titre de mes articles a toujours le format FCM100 - C&C - Titre, je m' | ||
| + | |||
| + | La ligne 55 supprime toutes les extensions .odt de la liste (puisque les fichiers de Google Drive n'ont pas d' | ||
| + | |||
| + | La ligne 57 vérifie qu'il n'y a pas de doublon, puisqu' | ||
| + | |||
| + | La liste est ensuite écrite dans un fichier temporaire (ce qui est pratique pour trouver les erreurs ou voir rapidement le nombre de fichiers). Le fichier est ensuite fermé et la fonction renvoie True (vrai). | ||
| + | |||
| + | |||
| + | **Function: update_database | ||
| This is the crux of the file. It essentially opens the article-list.txt file, and reads each line of it. For each non-empty line, it then does the following steps: | This is the crux of the file. It essentially opens the article-list.txt file, and reads each line of it. For each non-empty line, it then does the following steps: | ||
| Ligne 72: | Ligne 131: | ||
| Function: write_csv_database | Function: write_csv_database | ||
| - | This function uses csv.writer to create a valid CSV file. Line 95 dumps the keys of an entry (specifically, | + | This function uses csv.writer to create a valid CSV file. Line 95 dumps the keys of an entry (specifically, |
| - | Function: main | + | Fonction : update_database |
| + | |||
| + | C'est le point d' | ||
| + | Pour chaque ligne non vide, elle exécute les étapes suivantes : | ||
| + | • Découper la ligne selon le séparateur « - » (on obtient ainsi une ligne du genre [' | ||
| + | • Supprime le libellé FCM pour ne conserver que le numéro. | ||
| + | • Crée une entrée, constituée d'une paire clé/valeur vide, dans le dictionnaire. | ||
| + | • Complète les informations de cette entrée (si le titre est vide - certains de mes fichiers étaient mal nommés dans le passé -, elle rajoute la chaîne de caractères « Unknown » (inconnu). Elle supprime également d' | ||
| + | • dateFind est chargée de calculer une date estimée de ce numéro. | ||
| + | • Database.update est utilisée pour ajouter (ou mettre à jour) les informations concernant le numéro courant. | ||
| + | |||
| + | Une fois que la boucle for est terminée, le fichier est refermé, la valeur -1 de la base de données (la valeur originale de entryTemplate) est effacée et la base de données est renvoyée. | ||
| + | |||
| + | |||
| + | Fonction : write_database | ||
| + | |||
| + | C'est une fonction rapide qui utilise json.dumps pour simplement écrire le dictionnaire dans un fichier JSON. Il l' | ||
| + | |||
| + | Fonction : write_csv_database | ||
| + | |||
| + | Cette fonction utilise csv.writer pour créer un fichier CSV valide. La ligne 95 liste toutes les clés d'une entrée (ici, l' | ||
| + | |||
| + | |||
| + | **Function: main | ||
| This is just a function where I call the rest of the helper functions (and debugged issues). You can just as easily paste this into the if __name__ == “__main__” area, but the recommendation is to use a main function, to allow easier importing. | This is just a function where I call the rest of the helper functions (and debugged issues). You can just as easily paste this into the if __name__ == “__main__” area, but the recommendation is to use a main function, to allow easier importing. | ||
| Ligne 90: | Ligne 172: | ||
| Why Do Some Functions Return True? | Why Do Some Functions Return True? | ||
| - | This is mainly to indicate that the function completed correctly. It’s also a useful step if you want to support error handling. | + | This is mainly to indicate that the function completed correctly. It’s also a useful step if you want to support error handling.** |
| - | What Do I Do With The Database? | + | |
| + | Fonction : main | ||
| + | |||
| + | C'est tout simplement un endroit où j' | ||
| + | |||
| + | Les fonctions Drive | ||
| + | |||
| + | Fonction : cd | ||
| + | |||
| + | Cela recrée simplement une fonction cd à partir d'un Bash, mais renvoie également vers le répertoire (directory) original, de façon à ce que la commande d' | ||
| + | |||
| + | La fonction : update_drive | ||
| + | |||
| + | C'est un appel de la commande cd à l' | ||
| + | |||
| + | |||
| + | Pourquoi quelques fonctions renvoient True ? | ||
| + | |||
| + | C'est d' | ||
| + | |||
| + | |||
| + | **What Do I Do With The Database? | ||
| There are a few things you can do. Using something like OpenRefine, you can clean up your database (such as find out which files are lacking titles). Or else you can export it to a CSV and import it into Google Sheets or similar. | There are a few things you can do. Using something like OpenRefine, you can clean up your database (such as find out which files are lacking titles). Or else you can export it to a CSV and import it into Google Sheets or similar. | ||
| Ligne 111: | Ligne 214: | ||
| http:// | http:// | ||
| - | Stack Overflow cd command in Linux. | + | Stack Overflow cd command in Linux.** |
| + | |||
| + | Que fais-je avec la base de données ? | ||
| + | |||
| + | Il y a un certain nombre de choses que vous pouvez faire. En utilisant quelque chose comme OpenRefine vous pouvez nettoyer votre base (rechercher les fichiers qui n'ont pas de titre, par exemple). Ou bien vous pouvez l' | ||
| + | |||
| + | Enfin vous pouvez l' | ||
| + | |||
| + | Puis-je faire des recherches ? | ||
| + | |||
| + | Vous pouvez soit ouvrir le fichier JSON et rechercher manuellement, | ||
| + | |||
| + | J' | ||
| + | |||
| + | Lectures complémentaires | ||
| + | |||
| + | https:// | ||
| + | Les outils du CLI de Drive. | ||
| + | |||
| + | http:// | ||
| + | La commande cd de Linux dans StackOverflow. | ||
issue108/c_c.1462032741.txt.gz · Dernière modification : 2016/04/30 18:12 de auntiee
