Как искать текст в документах разных форматов по ключевым словам, используя Python?
Построение отчётов на основании большого количества файлов – рядовая задача. Но всё становится сложнее, если вместо одного формата исходных файлов, мы получаем кучу файлов разного расширения.
Ранее я говорил о том, как скачивали файлы из базы и распознавать их, здесь я расскажу о том, как вытаскивать информацию (для анализа данных для спринта), по ключевым словам, или фразам из документов разных форматов (.rtf,. doc,. docx,. xls,. xlsx,. pdf). Вообще эту тему можно отнести к text mining, data mining. Text Mining — это если простыми словами, то добыча информации из текстов. Data Mining – это примерно то же самое что и ™ только не в тексте, а большом наборе данных для последующего анализа.
В этой задаче столкнулся с такой проблемой как отсутствие нормальных библиотек для Python для парсинга информации с файлов!
Так как файлы были разных форматов (.rtf,. doc,. docx,. xls,. xlsx,. pdf) и что бы открыть и прочитать информацию из них помощью Python нужно было найти подходящие библиотеки. В. pdf были сканы, и мы вопрос с ними уже решили (об этом я рассказывал в предыдущей статье). Для работы с форматами. xls,. xlsx есть отличная библиотека pandas, которая на ура справляется с поставленной целью и не только. Pandas это высокоуровневая Python библиотека для анализа данных. В экосистеме Python, pandas является лучшей и быстроразвивающейся библиотекой для обработки и анализа данных. Мне приходится пользоваться ею практически каждый день!
Осталось решить вопрос с. rtf,. doc,. docx.
.rtf
Rich Text Format, RTF — это формат текста придуманный группой программистов из Microsoft и Adobe в 82 году.
Для работы с этим форматом использовал разные библиотеки в том числе pyth.
.doc — то же является текстовым форматом, но более лучшим чем предыдущий.
Для работы с ним использовал разные библиотеки, но также, как и с форматом. rtf проблема заключалась в том, что в документах были таблицы и нормально прочитать их не получалось никакой библиотекой (ни. rtf, ни. doc), просто текст читает без проблем если там нет таблиц (.rtf и. doc)!
В связи с этим. rtf и. doc просто приходилось конвертировать в формат. docx (про него ниже) и также сделал просто. exe-шник с помощью Python который конвертирует эти форматы в. docx.
Начиная с 2007 появился новый формат на основе XML — docx.
И так, с форматами. xls,. docx, проблем никаких не возникло. С помощью необходимых библиотек (docx, pandas, tkinter) работа с файлами, вытаскивание информации, по ключевым словам, или фразам была реализована! Сделан графический интерфейс (графический пользовательский интерфейс (ГПИ) (англ. graphical user interface, GUI)) также скомпилирована в. exe и добавлена инструкция.
How to search for a string in text files?
I want to check if a string is in a text file. If it is, do X. If it’s not, do Y. However, this code always returns True for some reason. Can anyone see what is wrong?
13 Answers 13
The reason why you always got True has already been given, so I’ll just offer another suggestion:
If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):
Python Search for a String in Text Files
In this Python tutorial, you’ll learn to search a string in a text file. Also, we’ll see how to search a string in a file and print its line and line number.
After reading this article, you’ll learn the following cases.
- If a file is small, read it into a string and use the find() method to check if a string or word is present in a file. (easier and faster than reading and checking line per line)
- If a file is large, use the mmap to search a string in a file. We don’t need to read the whole file in memory, which will make our solution memory efficient.
- Search a string in multiple files
- Search file for a list of strings
We will see each solution one by one.
Table of contents
How to Search for a String in Text File
Use the file read() method and string class find() method to search for a string in a text file. Here are the steps.
-
Open file in a read mode
Open a file by setting a file path and access mode to the open() function. The access mode specifies the operation you wanted to perform on the file, such as reading or writing. For example, r is for reading. fp= open(r’file_path’, ‘r’)
Once opened, read all content of a file using the read() method. The read() method returns the entire file content in string format.
Use the find() method of a str class to check the given string or word present in the result returned by the read() method. The find() method. The find() method will return -1 if the given text is not present in a file
If you need line and line numbers, use the readlines( ) method instead of read() method. Use the for loop and readlines() method to iterate each line from a file. Next, In each iteration of a loop, use the if condition to check if a string is present in a current line and print the current line and line number
Example to search for a string in text file
I have a ‘sales.txt’ file that contains monthly sales data of items. I want the sales data of a specific item. Let’s see how to search particular item data in a sales file.

Output:
Search file for a string and Print its line and line number
Use the following steps if you are searching a particular text or a word in a file, and you want to print a line number and line in which it is present.
- Open a file in a read mode.
- Next, use the readlines() method to get all lines from a file in the form of a list object.
- Next, use a loop to iterate each line from a file.
- Next, In each iteration of a loop, use the if condition to check if a string is present in a current line and print the current line and line number.
Example: In this example, we’ll search the string ‘laptop’ in a file, print its line along with the line number.
Output:
Note: You can also use the readline() method instead of readlines() to read a file line by line, stop when you’ve gotten to the lines you want. Using this technique, we don’t need to read the entire file.
Efficient way to search string in a large text file
All above way read the entire file in memory. If the file is large, reading the whole file in memory is not ideal.
In this section, we’ll see the fastest and most memory-efficient way to search a string in a large text file.
- Open a file in read mode
- Use for loop with enumerate() function to get a line and its number. The enumerate() function adds a counter to an iterable and returns it in enumerate object. Pass the file pointer returned by the open() function to the enumerate() .
- We can use this enumerate object with a for loop to access the each line and line number.
Note: The enumerate(file_pointer) doesn’t load the entire file in memory, so this is an efficient solution.
Example:
Example:
mmap to search for a string in text file
In this section, we’ll see the fastest and most memory-efficient way to search a string in a large text file.
Also, you can use the mmap module to find a string in a huge file. The mmap.mmap() method creates a bytearray object that checks the underlying file instead of reading the whole file in memory.
Example:
Output:
Search string in multiple files
Sometimes you want to search a string in multiple files present in a directory. Use the below steps to search a text in all files of a directory.
Example:
Output:
Search file for a list of strings
Sometimes you want to search a file for multiple strings. The below example shows how to search a text file for any words in a list.
Example:
Output:
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
Searching Text in Multiple Files in Python
In this blog, we will search some text or string in the multiple files.
Write text which you want to search
Write text in input box which you want to search, then press enter.
Output: Please enter text: machine
Output: You have entered “machine” word to search.
Get the current working directory
OS module in Python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
Get the current working directory
My current working directory is E://jupyter-notebook-workspace. But i want to search text in different directory.
Declare the path, in which you want to search text
I want to search text in this path “G:/data/path”. In this path iI have some files ans folders.
Create a function and list the directory
Create a function and change the directory in which you want to search text. After that list the directory and print the files.
os.chdir(path) — Change the current working directory to specified path.
os.listdir(path=’.’) —
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries ‘.’ and ‘..’ even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.