📜  Python程序计算一个句子中的单词

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

Python程序计算一个句子中的单词

数据预处理是文本分类中的一项重要任务。随着Python在数据科学领域的出现,必须有一定的速记才能在其他方面占据上风。本文讨论了计算句子中单词的方法,它从空格分隔的单词开始,但也包括出现特殊字符的方法。让我们讨论执行此操作的某些方法。

方法 #1:使用split()
split函数非常有用,通常是非常通用的方法来从列表中取出单词,但是一旦我们在列表中引入特殊字符,这种方法就会失败。

# Python3 code to demonstrate 
# to count words 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()
# to count words in string
res = len(test_string.split())
  
# printing result
print ("The number of words in string are : " +  str(res))
输出:


方法#2:使用regex(findall())

如果我们需要处理字符串中的标点符号或特殊字符的情况,则必须使用正则表达式。这是可以执行此任务的最优雅的方式。

# Python3 code to demonstrate 
# to count words 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())
# to count words in string
res = len(re.findall(r'\w+', test_string))
  
# printing result
print ("The number of words in string are : " +  str(res))
输出:


方法#3:使用sum() + strip() + split()
此方法在不使用正则表达式的情况下执行此特定任务。在此方法中,我们首先检查由所有字母组成的所有单词,如果是,则将它们添加到 sum 然后返回。

# Python3 code to demonstrate 
# to count words in string 
# using sum() + strip() + split()
import string
  
# initializing string  
test_string = "Geeksforgeeks,    is best @# Computer Science Portal.!!!"
  
# printing original string
print ("The original string is : " +  test_string)
  
# using sum() + strip() + split()
# to count words in string
res = sum([i.strip(string.punctuation).isalpha() for i in test_string.split()])
  
# printing result
print ("The number of words in string are : " +  str(res))
输出: