The post has been translated automatically. Original language: Russian
In this paper, we will use the Python programming language to analyze text files from the BBC News archive.
In the course of our work, we will complete several practical tasks: count the number of articles in the entertainment folder, load the contents of one of the articles into the computer's memory, display the text on the screen and determine the total number of characters in the file.
Question 1. Counting the number of articles in the entertainment folder.
First, you need to import the os library, which allows you to work with the file system and directories.
Importing a library:
import osSpecifying the path to the directory:
enter = os.listdir('/Users...../bbc/entertainment')Next, we use the len() function to determine the number of files in the directory.
Counting the number of articles:
len(articles)386
The entertainment folder contains 386 articles.
Question 2. Uploading the content of the article 339.txt into memory and output to the screen
The second step is to open the file. 339.txt located in the entertainment folder, load its contents into memory and display the text on the screen.
To do this, we use the open() function with the 'r' reading mode.
Opening and reading a file:
def main():
infile = open('bbc/entertainment/339.txt', 'r')
file_contents = infile.read()
infile.close()
print(file_contents)
main()
Actor Keanu Reeves, best known for his role in The Matrix films, was awarded a star on the famous Hollywood Walk of Fame.
The 40-year-old actor attended his star's unveiling ceremony with his mother, Patricia, and thanked her for inspiring him to become an actor. "When I was 15, I asked my mom if I could become an actor," Reeves said. She replied: "Do whatever you want." His star became the 2,277th, installed on the sidewalk of Hollywood Boulevard.
The actor, who was born in Beirut, the capital of Lebanon, also spoke about how he dropped out of school to devote himself to an acting career. "Hollywood was calling me," he said. "So I got in my car, a 1969 British Volvo, painted dark green racing, with holes in the floor and bricks supporting the seats. I was a young man full of hopes and dreams."
Reeves first gained fame with the teen comedy "The Incredible Adventures of Bill and Ted." He later starred in high-grossing films such as "Speed," The Matrix film series, and others, as well as smaller-scale films including "My Personal State of Idaho."
Question 3. Determining the file length 339.txt
At the final stage, it is necessary to determine the total length of the article text.
sum(len(i) for i in news)Result: 1258 characters
Conclusion
Thus, in the course of this work, we solved several practical problems using Python, which helped us acquire the skills to work with this programming language.
In the process, we learned how to use the os library to view the contents of directories and count the number of files, open and read text documents, load their contents into computer memory and display information on the screen.
In addition, we got acquainted with creating and calling our own functions, using the read() methods to read the contents of the file and close() to close it, as well as using the len() function to determine the total number of characters in the text.
As a result, we gained hands-on experience working with text data and better understood how Python can be used to read, process, and analyze information from files.
В данной работе мы будем использовать язык программирования Python для анализа текстовых файлов из новостного архива BBC News.
В ходе работы мы выполним несколько практических заданий: подсчитаем количество статей в папке entertainment, загрузим содержимое одной из статей в память компьютера, выведем текст на экран и определим общее количество символов в файле.
Вопрос 1. Подсчёт количества статей в папке entertainment.
Для начала необходимо импортировать библиотеку os, которая позволяет работать с файловой системой и директориями.
Импорт библиотеки:
import osУказание пути к директории:
enter = os.listdir('/Users...../bbc/entertainment')Далее используем функцию len(), чтобы определить количество файлов в директории.
Подсчёт количества статей:
len(articles)386
В папке entertainment содержится 386 статей.
Вопрос 2. Загрузка содержимого статьи 339.txt в память и вывод на экран
На втором этапе необходимо открыть файл 339.txt, расположенный в папке entertainment, загрузить его содержимое в память и вывести текст на экран.
Для этого используем функцию open() с режимом чтения 'r'
Открытие и чтение файла:
def main():
infile = open('bbc/entertainment/339.txt', 'r')
file_contents = infile.read()
infile.close()
print(file_contents)
main()
Актёр Киану Ривз, наиболее известный по своей роли в фильмах «Матрица», был удостоен звезды на знаменитой Голливудской Аллее славы.
40-летний актёр присутствовал на церемонии открытия своей звезды вместе со своей матерью Патрицией и поблагодарил её за то, что она вдохновила его стать актёром. «Когда мне было 15 лет, я спросил маму, можно ли мне стать актёром», — рассказал Ривз. Она ответила: "Делай всё, что хочешь." Его звезда стала 2 277-й, установленной на тротуаре Голливудского бульвара.
Актёр, родившийся в столице Ливана — Бейруте, также рассказал о том, как бросил школу, чтобы посвятить себя актёрской карьере. "Голливуд звал меня", — сказал он. "Поэтому я сел в свою машину — британский Volvo 1969 года выпуска, окрашенный в тёмно-зелёный гоночный цвет, с дырами в полу и кирпичами, поддерживающими сиденья. Я был молодым человеком, полным надежд и мечтаний."
Ривз впервые приобрёл известность благодаря подростковой комедии "Невероятные приключения Билла и Теда." Позже он снялся в таких кассовых фильмах, как "Скорость", серии фильмов "Матрица" и других, а также в менее масштабных картинах, включая "Мой личный штат Айдахо."
Вопрос 3. Определение длины файла 339.txt
На заключительном этапе необходимо определить общую длину текста статьи.
sum(len(i) for i in news)Результат: 1258 символов
Заключение
Таким образом, в ходе выполнения данной работы мы решили несколько практических задач с помощью Python, которые помогли нам приобрести навыки работы с этим языком программирования.
В процессе работы мы научились использовать библиотеку os для просмотра содержимого директорий и подсчёта количества файлов, открывать и читать текстовые документы, загружать их содержимое в память компьютера и выводить информацию на экран.
Кроме того, мы познакомились с созданием и вызовом собственных функций, использованием методов read() для чтения содержимого файла и close() для его закрытия, а также применением функции len() для определения общего количества символов в тексте.
В результате мы получили практический опыт работы с текстовыми данными и лучше поняли, как Python можно использовать для чтения, обработки и анализа информации из файлов.
Comments 2
Newest Popular