Как посчитать количество слов в питоне
Перейти к содержимому

Как посчитать количество слов в питоне

  • автор:

How to Count Words in String in Python

How to Count Words in String in Python

  1. Use the split() and len() Methods to Count Words in Python String
  2. Use RegEx Module to Count Words in Python String
  3. Use sum() , strip() and split() Methods to Count Words in Python String
  4. Use the count() Method to Count Words in Python String Python

This tutorial will introduce how to count words in string Python.

Use the split() and len() Methods to Count Words in Python String

split() is a built-in method in Python that separates the words inside a string by using a specific separator and returns an array of strings. This method accepts at most two parameters as an argument:

  • separator (optional) — It acts as a delimiter (e.g. commas, semicolon, quotes, or slashes). Specifies the boundary on which to separate in the string. The default separator is any whitespace (space, newline, tab, etc.) if the separator is not specified.
  • maxsplit (optional) — It defines the maximum number of splits. The default value of maxsplit if not defined is -1 , which means that it has no limits and will split the string into multiple chunks.

Syntax of split() :

str.split(separator, maxsplit) 

len() is also a Python built-in method, which returns the number of strings in an array or counts the length of items in an object. This method only accepts one parameter: a string, bytes, list, object, set, or a collection. It will raise a TypeError exception if the argument is missing or invalid.

len(s) 

Let’s see how the split() and len() methods counts the words in a string.

Example 1: No Parameters

# initialize string text = "The quick brown fox jumps over the lazy dog"  # default separator: space result = len(text.split())  print("There are " + str(result) + " words.") 
There are 9 words. 

Example 2: With the separator Parameter

# initialize string bucket_list = "Japan, Singapore, Maldives, Europe, Italy, Korea"  # comma delimiter result = len(bucket_list.split(","))  # Prints an array of strings print(bucket_list.split(","))  print("There are " + str(result) + " words.") 
['Japan', ' Singapore', ' Maldives', ' Europe', ' Italy', ' Korea'] There are 6 words. 

The split() method will return a new list of strings, and the len() counts the string inside the list.

Example 3: With the separator and maxsplit Parameters

# initialize string bucket_list = "Japan, Singapore, Maldives, Europe, Italy, Korea"  # comma delimiter result = len(bucket_list.split(",", 3))  # Prints an array of strings print(bucket_list.split(",", 3))  print("There are " + str(result) + " words.") 
['Japan', ' Singapore', ' Maldives', ' Europe, Italy, Korea'] There are 4 words. 

maxsplit splits only the first three commas in the bucket_list . If you set the maxsplit , the list will have a maxsplit+1 item.

['Japan', ' Singapore', ' Maldives, Europe, Italy, Korea'] There are 3 words. 

The split() method breaks down large strings into smaller ones. Therefore, the counting of words in the array of strings will be based not exactly on the words but on how the split separator is defined.

Use RegEx Module to Count Words in Python String

Regular Expression, regex or regexp for short, is a very powerful tool in searching and manipulating text strings; this can be used for data preprocessing, validation purposes, finding a pattern in a text string, and so on. Regex can also help count words in a text string in scenarios where it has punctuation marks or special characters that are not needed. Regex is a Python built-in package, so we just need to import the package re to start using it.

# import regex module import re  # initialize string text = "Python !! is the be1st $$ programming language @"  # using regex findall() result = len(re.findall(r"\w+", text))  print("There are " + str(result) + " words.") 
There are 6 words. 

Use sum() , strip() and split() Methods to Count Words in Python String

This approach counts the words without using regex. The sum() , strip() , and split() are all built-in methods in Python. We’ll briefly discuss each method and its functionalities.

The sum() method adds the items up from left to right and returns the sum. The method takes two parameters:

  • iterable (required) — a string, list, tuple, etc., to add up. These should be numbers.
  • start (optional) — A number added to the sum or the return value of the method.
sum(iterable, start) 

The next one is the strip() method, which returns a copy of the string stripped both the leading and the trailing whitespaces if no argument; otherwise, this removes the string defined in the argument.

  • chars (optional) — specifies the string to be removed from the left and right parts of the text.

Syntax of string.strip() :

string.strip(chars) 

Finally, the split() method, was already discussed before this approach.

Now, let’s use these methods together to count words in a string. First, we need to import the string , a Python built-in module, before using its functionalities.

import string  # initialize string text = "Python !! is the be1st $$ programming language @"  # using the sum(), strip(), split() methods result = sum([i.strip(string.punctuation).isalpha() for i in text.split()])  print("There are " + str(result) + " words.") 
There are 5 words. 

Use the count() Method to Count Words in Python String Python

The count() method is a Python built-in method. It takes three parameters and returns the number of occurrences based on the given substring.

  • substring (required) — a keyword to be searched in the string
  • start (option) — index as to where the search starts
  • end (option) — index as to where the search ends

The index starts from 0 in Python.

Syntax of count() :

string.count(substring, start, end) 

This method is different from the previous method since it does not return the total words found in the string but the number of occurrences found given the substring. Let’s see how this method works from the example below:

# initialize string text = "Python: How to count words in string Python" substring = "Python"  total_occurrences = text.count(substring)  print("There are " + str(total_occurrences) + " occurrences.") 
There are 2 occurrences. 

In this method, it doesn’t matter if the substring is a whole word, phrase, letter, or any combination of characters or numbers.

In summary, you can choose any of these approaches depends on your use case. For space-separated words, we can use the straightforward approach: the functions split() or len() . For filtering text strings to count words without special characters, use the regex module. Create a pattern that counts the words that do not include certain characters. Without using regex , use the alternative which is the combination of sum() + strip() + split() methods. Lastly, the count() method can also be used for counting the specific word found in the string.

Related Article — Python String

  • How to Remove Commas From String in Python
  • How to Check a String Is Empty in a Pythonic Way
  • How to Convert a String to Variable Name in Python
  • How to Remove Whitespace From a String in Python
  • How to Extract Numbers From a String in Python
  • How to Convert String to Datetime in Python

Copyright © 2024. All right reserved

Как посчитать количество слов в строке python

Обложка для статьи

В Python есть много встроенных функций и методов, которые упрощают обработку строк. Одна из часто встречающихся задач — подсчет количества слов в строке. Это может быть полезно, например, при анализе текстов или при работе с данными, связанными с языком. В этой статье мы рассмотрим несколько способов, как посчитать количество слов в строке в Python.

Методы для подсчета количества слов в строке

Для подсчета количества слов в строке в Python существует несколько методов. Рассмотрим наиболее распространенные из них.

Использование метода split()

Метод split() является одним из самых простых и наиболее используемых способов для подсчета количества слов в строке в Python. Этот метод разбивает строку на список слов, используя разделитель, который задается в качестве аргумента метода. По умолчанию разделителем является пробел.

Вот как можно использовать метод split() для подсчета количества слов в строке:

string = "Python is a popular programming language" word_list = string.split() print(len(word_list))

Здесь мы определяем строку «Python is a popular programming language» и используем метод split() для разбиения ее на список слов. Затем мы используем функцию len() для подсчета количества элементов в списке, которое и будет количеством слов в исходной строке.

Этот подход работает не только для простых строк, но и для строк, содержащих знаки препинания и другие символы. Однако, если строка содержит множественные пробелы или другие символы-разделители, метод split() может дать неправильный результат.

Например, если строка содержит несколько пробелов между словами, метод split() может воспринимать их как отдельные элементы, что приведет к неправильному результату. Для таких случаев необходимо использовать более продвинутые методы.

Метод count()

Метод count() — это встроенный метод в Python, который используется для подсчета количества вхождений подстроки в строку. В данном случае, мы можем использовать его для подсчета количества слов в строке.

Метод count() принимает один обязательный аргумент — подстроку, которую нужно искать в строке, и два необязательных аргумента — start и end , которые указывают начальную и конечную позиции в строке для поиска подстроки. Если аргументы start и end не указаны, метод будет искать подстроку во всей строке.

Пример использования метода count() для подсчета количества слов в строке:

sentence = "The quick brown fox jumps over the lazy dog" word_count = sentence.count(" ") + 1 print("Количество слов в строке:", word_count)

В этом примере мы сначала определяем строку sentence , содержащую несколько слов. Затем мы используем метод count() для подсчета количества пробелов в строке, добавляем 1, и получаем количество слов в строке. Результат выводится на экран.

Этот метод может быть полезен, если вам нужно быстро подсчитать количество слов в строке без использования регулярных выражений или метода split() . Однако стоит учитывать, что он может не работать должным образом, если в строке есть знаки препинания или другие символы, отличные от пробелов, используемых для разделения слов.

Использование регулярных выражений

Использование регулярных выражений — это еще один способ подсчета количества слов в строке. В Python есть модуль re , который позволяет работать с регулярными выражениями.

Регулярные выражения — это формальный язык поиска и манипулирования подстроками в тексте. Они используются для поиска определенных паттернов в строке, таких как слова, числа, электронные адреса и т.д.

Для подсчета количества слов в строке с помощью регулярных выражений, мы можем использовать функцию findall() из модуля re . Эта функция ищет все совпадения с регулярным выражением и возвращает список найденных строк.

Вот пример использования регулярного выражения для подсчета количества слов в строке:

import re string = "Это пример строки для подсчета слов" word_list = re.findall(r'\b\w+\b', string) print("Количество слов в строке:", len(word_list))

В этом примере мы импортировали модуль re , определили строку, которую мы хотим проанализировать, и затем использовали функцию findall() с регулярным выражением r’\b\w+\b’ . Это регулярное выражение соответствует словам, которые состоят из одного или более буквенно-цифровых символов и отделены от других символов пробелами или границами слов.

Функция findall() вернет список найденных слов, который мы затем передадим в функцию len() для подсчета количества слов.

Как посчитать количество слов в питоне

Рассмотрим работу со строками на небольшом примере, который будет представлять программу подсчета слов.

Пусть весь код программы будет выглядеть следующим образом:

# Программа подсчета слов в файле import os def get_words(filename): with open(filename, encoding="utf8") as file: text = file.read() text = text.replace("\n", " ") text = text.replace(",", "").replace(".", "").replace("?", "").replace("!", "") text = text.lower() words = text.split() words.sort() return words def get_words_dict(words): words_dict = dict() for word in words: if word in words_dict: words_dict[word] = words_dict[word] + 1 else: words_dict[word] = 1 return words_dict def main(): filename = input("Введите путь к файлу: ") if not os.path.exists(filename): print("Указанный файл не существует") else: words = get_words(filename) words_dict = get_words_dict(words) print(f"Кол-во слов: ") print(f"Кол-во уникальных слов: ") print("Все использованные слова:") for word in words_dict: print(word.ljust(20), words_dict[word]) if __name__ == "__main__": main()

Здесь в функции get_words() производится начальная сегментация текста на слова. Пи этом все пунктуационные знаки удаляются, а переводы стоки заменяется на пробелы. Затем происходит разбитие текста на слова. В качестве разделителя по умолчанию применяется пробел.

Далее в функции get_words_dict() получаем словарь из слов, где ключ — это уникальное слово, а значение — количество вхождений данного слова в тексте.

В функции main осуществляется ввод пути к файлу и вызов выше определенных функций, а также вывод все статистики.

Консольный вывод программы:

Введите путь к файлу: C:\SomeDir\hello.txt Кол-во слов: 66 Кол-во уникальных слов: 54 Все использованные слова: благодетель 2 в 1 всего 1 вы 1 горчичным 1 ее 1 ежели 3 еще 1 .

Как посчитать количество слов в тексте Python

Всем добрый вечер! Есть такая простая задача: Есть список слов, а потом вводится неограниченное кол-во строк со словами. Нужно проверить, есть ли слово из списка в строках и вывести кол-во строк, где есть хоть одно это слово.

текст про яблоко и яблоки текст про яблок яблоко вкусное на дереве яблоко с яблоком витамины в 
6 # так как 6 строк, в которых хоть 1 раз упоминается слово с корнем **яблок** 

Отслеживать

49.3k 17 17 золотых знаков 57 57 серебряных знаков 101 101 бронзовый знак

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *