📜  Python|字符串中的单词长度

📅  最后修改于: 2022-05-13 01:54:55.766000             🧑  作者: Mango

Python|字符串中的单词长度

我们有时会遇到需要获取字符串中存在的所有单词长度的情况,这可能是使用幼稚方法完成的繁琐任务。因此,使用速记来执行此任务总是很有用的。让我们讨论实现这一目标的某些方法。

方法 #1:使用split() + len()
使用 split函数,我们可以将字符串拆分为单词列表,如果希望完成此特定任务,这是最通用和推荐的方法。但缺点是在字符串中包含标点符号的情况下它会失败。 len() 用于计算字符串长度。

# Python3 code to demonstrate 
# Words lengths in String
# using split()
  
# initializing string 
test_string = "Geeksforgeeks is best Computer Science Portal"
  
# printing original string
print ("The original string is : " + test_string)
  
# using split()
# Words lengths in String
res = list(map(len, test_string.split()))
  
# printing result
print ("The list of words lengths is : " + str(res))
输出 :
The original string is : Geeksforgeeks is best Computer Science Portal
The list of words lengths is : [13, 2, 4, 8, 7, 6]

方法#2:使用regex( findall() ) + len()
在包含所有特殊字符和标点符号的情况下,如上所述,使用拆分在字符串中查找单词的传统方法可能会失败,因此需要正则表达式来执行此任务。 findall函数在过滤字符串并提取忽略标点符号的单词后返回列表。 len() 用于计算字符串长度。

# Python3 code to demonstrate 
# Words lengths in String
# using regex( findall() )
import re
  
# initializing string 
test_string = "Geeksforgeeks, is best @# Computer Science Portal.!!!"
  
# printing original string
print ("The original string is : " + test_string)
  
# using regex( findall() )
# Words lengths in String
res = list(map(len, re.findall(r'\w+', test_string)))
  
# printing result
print ("The list of words lengths is : " + str(res))
输出 :
The original string is : Geeksforgeeks is best Computer Science Portal
The list of words lengths is : [13, 2, 4, 8, 7, 6]