📜  计算字符串中单词和字符数的Python程序

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

计算字符串中单词和字符数的Python程序

给定一个字符串。任务是找出字符串中存在的单词和字符数。

例子:

Input: Geeksforgeeks is best Computer Science Portal
Output:
The number Of Words are : 6
The Number Of Characters are : 45

Input: Hello World!!!
Output:
The original string is : Hello World!!!
The number of words in string are : 2
The number of words in string are :  14

使用 len()函数计算字符串中存在的字符数。您还可以使用 for 循环来计算字符

char=0
for i in string:
    char=char+1

计数用

方法 1:使用split()

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

Python3
# 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))
print("The number of words in string are : ", len(test_string))


Python3
import re
test_string = "GeeksForGeeks is a learning platform"
 
# original string
print("The original string is : " + test_string)
 
# using regex (findall()) function
res = len(re.findall(r'\w+', test_string))
 
# total no of words
print("The number of words in string are : " + str(res))
print("The number of Characters in string are : ", len(test_string))


Python3
import string
 
 
test_string = "GeeksForGeeks is a learning platform"
 
# printing original string
print("The original string is: " + test_string)
 
# using sum() + strip() + split() function
res = sum([i.strip(string.punctuation).isalpha() for i in
           test_string.split()])
 
# no of words
print("The number of words in string are : " + str(res))
print("The number of characters in string are : ", len(test_string))


输出:

方法二:使用regex模块

这里 findall()函数用于计算正则表达式模块中可用的句子中的单词数。

蟒蛇3

import re
test_string = "GeeksForGeeks is a learning platform"
 
# original string
print("The original string is : " + test_string)
 
# using regex (findall()) function
res = len(re.findall(r'\w+', test_string))
 
# total no of words
print("The number of words in string are : " + str(res))
print("The number of Characters in string are : ", len(test_string))

输出:

方法三:使用 sum()+ strip()+ split()函数

这里我们首先检查给定句子中的所有单词,并使用 sum()函数将它们相加。

蟒蛇3

import string
 
 
test_string = "GeeksForGeeks is a learning platform"
 
# printing original string
print("The original string is: " + test_string)
 
# using sum() + strip() + split() function
res = sum([i.strip(string.punctuation).isalpha() for i in
           test_string.split()])
 
# no of words
print("The number of words in string are : " + str(res))
print("The number of characters in string are : ", len(test_string))

输出: