Okay, it's finally time to do a little data wrangling
for ourselves. We're going to look at parsing CSV files in Python.
In this case, we're going to be reading the CSV data into
our program and creating on dictionary for each item in that
file. So you might ask yourself, why would we do something
like this? Why not just open it in a spreadsheet application?
One reason, is because if the file is big, let's tens
or even hundreds of megabytes, opening it in a spreadsheet application
like Excel can be slow, inefficient or maybe even
impossible. Your app might do the software equivalent of
this. Another reason we might want to programmatically process
tabular data, is because we might have a whole
lot of files to process. So, doing it manually
in the spreadsheet application simply isn't an option. Alright,
let's take a look at the code provided. Here
you can see, we have a parse file application.
In this exercise, we're going to be working with
the Beatles' disckography data, one more time. You'll be
working in the parse file function in the provided
code. And, your assignment is to use the Python
function split to parse each row into a dictionary.
For each dictionary, the names of the fields will
serve as the keys and the value you find on a given row will serve as the values
for those keys. You should produce an array of
these dictionaries, one dictionary for each item remember. And you
should return that array from the parse file function.
Now, one final instruction here, is that rather than processing
the entire file, you should only parse the first
ten lines in this file. If you go beyond that,
you run into trouble with this particular dataset. Since this
is the first exercise we're looking at in this course.
Let me talk a little bit about this test
function here. We're providing this as a means for you
to test your implementation of parse file. This will run
a little bit of code which calls the parse file
function and sample the result that it gets back
from parse file, checking to see if it has the
expected values. When you actually submit your program, we'll be
running some different test code, possibly on a different dataset.
حسنًا، لقد حانت أخيرًا لحظة إجراء تحويل البيانات وتخطيطها
.لأنفسنا. سنلقي نظرة على تحليل ملفات CSV في Python
في هذه الحالة، سنقوم بقراءة بيانات CSV في
البرنامج وإنشاء قاموس لكل عنصر في هذا
الملف. لذا يمكنك أن تسأل نفسك، لماذا يتعين علينا القيام بشيء
كهذا؟ لماذا لا يتم فتحه في تطبيق جدول بيانات وحسب؟
هناك سبب واحد وهو إذا كان الملف كبيرًا، فلنقل بحجم عشرات
أو مئات الميجابايت، فإن فتحه في تطبيق جدول بيانات
مثل Excel قد يكون بطيئًا أو غير فعّال أو ربما
غير ممكن. قد يقوم التطبيق بالمكافئ البرمجي
لهذا. هناك سبب آخر وراء أننا نريد معالجة
البيانات الجدولية برمجيًا، وهو أنه قد يوجد لدينا الكثير
من الملفات لمعالجتها. لذا، لا يعد إجراء ذلك يدويًا
،في تطبيق جداول البيانات خيارًا. حسنًا
فلنلقِ نظرة على التعليمة البرمجية المقدمة. وهنا
.يمكنك رؤية أنه يوجد لدينا تطبيق تحليل ملفات
في هذا التمرين، سنقوم بالعمل باستخدام
بيانات تصوير القرص لفرقة Beatles، مرة أخرى. وستعمل في
دالة parse file في التعليمة البرمجية
المقدمة. ومهمتك هي استخدام تجزئة دالة Python
.لتحليل كل صف في قاموس
بالنسبة إلى كل قاموس، ستعمل أسماء الحقول
كمفاتيح في حين ستعمل القيمة التي تجدها في صف معين كقيم
لتلك المفاتيح. يجب عليك إنتاج أي صفيف
من هذه القواميس، قاموس واحد لكل عنصر تتذكره. ويجب عليك
.إرجاع هذا الصفيف من دالة parse file
والآن، تعليمة أخيرة وهي أنه بدلاً من معالجة
الملف بالكامل، يجب عليك تحليل السطور
،العشرة الأولى فقط في هذا الملف. إذا تجاوزت ذلك
فستواجه مشكلات في مجموعة البيانات الخاصة هذه. وحيث إن
.هذا هو أول تمرين نتناوله في هذه الدورة التدريبية
فدعنا نتحدث قليلاً عن دالة الاختبار
هذه هنا. نحن نقدم هذا الاختبار كوسيلة لك
لاختبار تنفيذ الدالة parse file. وسيؤدي ذلك إلى
تشغيل قدر بسيط من التعليمة البرمجية التي تستدعي دالة
parse file وأخذ عينة من النتيجة التي يتم إرجاعها
من دالة parse file، مع التحقق لمعرفة ما إذا كانت تتضمن
قيمًا متوقعة أم لا. عند إرسال البرنامج في الواقع، ستقوم بتشغيل
.تعليمة برمجية لاختبار مختلفة، ربما على قاعدة بيانات مختلفة
Ok, finalmente é a hora de fazer uma pequena preparação de dados
sozinhos. Vamos dar uma olhada em como analisar arquivos CSV no Python.
Neste caso, vamos ler os dados CSV no
nosso programa e criar um dicionário para cada item naquele
arquivo. Você pode estar se perguntando por que faríamos
isso. Por que não simplesmente abrir em um aplicativo de planilha?
Um motivo é que o arquivo é grande, com dezenas
ou centenas de megabytes. Abri-lo em um aplicativo de planilha
como o Excel pode ser lento, ineficaz ou até
impossível. O seu aplicativo pode fazer o equivalente a
isto. Outro motivo pelo qual podemos querer processar
dados tabulares via programa é que podemos ter
muitos arquivos para processar. Então, fazer manualmente
no aplicativo de planilha não é uma opção. Tudo bem,
vamos olhar o código fornecido. Aqui,
é possível ver que há um aplicativo de parse_file.
Neste exercício, vamos trabalhar com
os dados da discografia dos Beatles mais uma vez. Você irá
trabalhar na função de parse file no código
fornecido. A sua tarefa é usar a função
split do Python para analisar cada linha em um dicionário.
Em cada dicionário, os nomes dos campos
servirão como chaves e o valor que você encontra em uma certa linha serve como valores
daquelas chaves. Você deve produzir um array a partir
destes dicionários, um dicionário para cada item. E deve
retornar aquele array a partir da função de parse file.
A última instrução é que em vez de processar
o arquivo inteiro, você deve analisar apenas as
primeiras 10 linhas dele. Se for além,
terá problemas com este conjunto de dados em particular. Já que este
é o primeiro exercício que estamos vendo neste curso,
vou falar um pouco sobre esta função
test aqui. Estamos possibilitando formas de você
testar sua implementação de parse_file. Isso vai executar
alguns códigos, o que chama a função de
parse file e testa o resultado que obtém do
parse_file, verificando para saber se ele tem
os valores esperados. Quando você enviar seu programa, vamos
executar um código de teste diferente, provavelmente em um conjunto de dados diferente.
我们终于可以进行数据再加工了
我们来看一下在 Python 中如何解析 CSV 文件
在这里 我们要将 CSV 数据读入我们的程序
并为文件中的每一项创建一个字典
你可能会问 我们为什么要这样做?
为什么不直接用电子表格应用打开文件?
其中一个原因是因为文件过大 可能有几十 甚至几百兆
在 Excel 等电子表格应用中打开
速度会非常慢 效率也很低 有时甚至是不可能的
你的应用所完成的软件任务就相当于这个
我们以编程方式来处理表格数据的另一个原因是
因为 我们需要处理的文件可能有很多
所以 我们根本不可能
在电子表格应用中手动处理
让我们看一下这里的代码
可以看到 我们这里有个解析文件应用
在这个练习中
我们仍然使用披头士的唱片数据
你将使用已给代码中的解析文件函数
你的任务就是利用 Python 的 split 函数
将每一行解析成字典
在每一个字典中 字段名是关键字
每一行的值是这些关键字的值
你需要将这些字典生成数组
记住 每一项都要有相应的字典
然后 你需要在解析文件函数中返回这个数组
最后一点要说明的是 不要处理整个文件
你应该只解析文件的前十行
如果你的解析对象超出数据集的前十行
你就会遇到麻烦
由于这是我们这节课的第一个练习
我来讲一下这里的测试函数
我们为你提供了测试函数
以方便你测试你运行的解析文件是否正确
这个代码会调用解析文件函数
并从解析文件中抽取结果样本
检查其是否是预期值
当你提交你的程序时
我们可能会在不同的数据集上运行一些其它测试代码