search
HomeBackend DevelopmentPython TutorialCalculate the length of words in a string using Python

Calculate the length of words in a string using Python

Sep 13, 2023 am 11:29 AM
stringcalculateword

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. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool