Home  >  Article  >  Backend Development  >  Calculate the length of words in a string using Python

Calculate the length of words in a string using Python

PHPz
PHPzforward
2023-09-13 11:29:031185browse

Calculate the length of words in a string using Python

Finding the length of individual words in a given input string using Python is a problem that must be solved. We want to count the number of characters of each word in a text input and display the results in a structured style such as a list. The task requires breaking up the input string and separating each word. Then calculate the length of each word based on the number of characters in it. The basic goal is to create a function or procedure that can efficiently receive input, determine word length, and output results in a timely manner. Addressing this issue is critical in a variety of applications, including text processing, natural language processing, and data analysis, where word length statistics can provide insightful information and enable additional analysis.

usage instructions

  • Use loops and split() function

  • Use the map() function with len and split()

  • Use the re.split() method in the re module

  • Use dictionary to store word length

Using loops and split() function

A basic and simple Python text processing and analysis technique is to get the word length using a loop and the split() function. By using this technique to break down the input string into its component words, we can determine the length of each word by repeatedly checking the list of words. In this method, the split() function is crucial as it essentially tokenizes the input text based on space characters, thus separating words from each other. The resulting word list serves as the basis for the rest of our word length calculations. This technique is an important part of any text analysis toolset because it is effective and simple at understanding and extracting important information from text input.

algorithm

  • Define a function findWordLengths that takes the input string as a parameter.

  • Use the split() function to split the input string into individual words, using spaces as delimiters to separate them. Store the results in a list called words.

  • Initialize an empty list "wordLengths" to store the length of words.

  • For each word in the word list, do the following:

  • a. Use the len() function to calculate the length of the current word.

    b. Append the length of the current word to the "wordLengths" list.

  • Return the "wordLengths" list.

Example

def findWordLengths(input_string):
   words = input_string.split()
   wordLengths = []
   for word in words:
      wordLengths.append(len(word))
   return wordLengths


input_string = "Today feels like a productive day"
result = findWordLengths(input_string)
print("The words lengths are as:", result)

Output

The words lengths are as: [5, 5, 4, 1, 10, 3]

Using the map() function with len and split()

The method of determining word length in Python combines the map() function with len and split() to provide an elegant and efficient answer to the problem of working with text data. This approach leverages the power of Python's built-in functions, which can be combined to quickly determine the length of individual words in an input string. The split() method uses spaces as delimiters, effectively splitting the input string into separate words, and is the basis of this strategy. The result was the creation of a list of terms that served as the basis for further investigation. Using the map() method, we change this list into an iterable list containing the lengths of all words by applying the len() function to each word.

algorithm

  • Define a function findWordLengths that takes the input string as its parameter. This parameter will contain our input string.

  • Use the split() function to split the input string into individual words, using spaces as delimiters. Store the results in a list called words.

  • Use the map() function to apply the len() function to each word in the word list, because the len() function mainly calculates the length. This will produce an iteration containing the length of a single word.

  • Convert the iterable obtained from map() to a list to get the length of a single word.

  • Returns a list of word lengths.

Example

def findWordLengths(input_string):
   words = input_string.split()
   wordLengths = list(map(len, words))
   return wordLengths


input_string = "Hello my name is Rahul"
result = findWordLengths(input_string)
print("The words lengths are as:", result)

Output

The words lengths are as: [5, 2, 4, 2, 5]

Use the re.split() method in the re module

Regular expressions are an effective tool for text modification and pattern matching. By intelligently detecting whitespace characters as word separators, the re.split() function can serve as a reliable technique for tagging phrases into words in this case. To split words accurately, the regular expression pattern r's ' matches one or more consecutive whitespace letters. This method performs very well when handling different input text formats, allows different whitespace patterns, and provides accurate word length calculations. Its use of regular expressions makes it efficient even when processing large amounts of input data. Additionally, the lack of other libraries simplifies implementation.

algorithm

  • Enter a sentence containing the word.

  • Use the re.split() method and the regular expression r'\s ' to split the sentence into words.

  • Initialize an empty list to store word length.

  • Iterate over each word in the word list:

  • a. Calculate the length of the current word.

  • b. Appends the word length to the word length list.

  • Output word length list.

示例

import re

def word_lengths(sentence):
   
   words = re.split(r'\s+', sentence)
   
   word_lengths = []
   
   for word in words:
      length = len(word)
      word_lengths.append(length)
   
   return word_lengths

sentence = "This is a sample sentence"
result = word_lengths(sentence)
print(result)

输出

[4, 2, 1, 6, 8]

使用字典存储单词长度

使用字典保存单词长度来确定字符串中单词长度的方法将 Python 内置数据结构的有效性与简单的算法相结合,以提供有效且适应性强的结果。该技术通过使用 len() 函数迭代计算字典中每个单词的长度,为字典中的每个单词生成键值对。给出单词的长度作为匹配值,并将单词设置为键。由于这个清晰简单的过程,字长的收集是精确和有效的。

生成的词典提供每个单词对应的单词长度,捕获文本的广泛视图。为了进一步处理或分析数据,这种格式可以轻松检索字长。

算法

  • 输入包含单词的句子。

  • 使用 split() 方法将句子拆分为单词,这将为我们的输入字符串创建单词列表。

  • 初始化一个空字典来存储单词长度。

  • 迭代单词列表中的每个单词,如下所示:

  • a。计算当前单词的长度。

  • b。向字典中添加一个条目,以单词为键,以单词长度为值。

  • 输出包含单词长度的字典。

示例

def word_lengths(sentence):

   words = sentence.split()
   word_lengths_dict = {}
   
   for word in words:
      length = len(word)
      word_lengths_dict[word] = length
   
   return word_lengths_dict

sentence = "This is how the length of words is calculated"
result = word_lengths(sentence)
print(result)

输出

{'This': 4, 'is': 2, 'how': 3, 'the': 3, 'length': 6, 'of': 2, 'words': 5, 'is': 2, 'calculated': 10}

结论

总而言之,我们研究了四种不同的 Python 方法来计算字符串中的单词长度。对于简单的工作,前两种方法(使用循环和 split() 函数或带有 len 和 split() 的 map() 函数)提供了简单性和有效性。第三个选项利用 re 模块中的 re.split() 方法,展示了正则表达式的强大功能,适合在复杂的文本处理应用程序中使用。最后但并非最不重要的一点是,使用字典来跟踪单词长度提供了一种系统且实用的方法来检索和处理单词数据。每种方法都具有特定的优点,使程序员能够根据特定需求和编码偏好选择最佳选项。

The above is the detailed content of Calculate the length of words in a string using Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete