📜  Python - 具有特定字母的字数

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

Python - 具有特定字母的字数

给定字符串单词,提取具有特定字母的单词数。

方法 #1:使用列表推导 + len() + split()

这是可以执行此任务的方法之一。在这里,我们使用 split() 执行从字符串中提取单词的任务,循环用于迭代单词以检查字母是否存在,len() 用于获取带有字母的单词数。

Python3
# Python3 code to demonstrate working of 
# Count of Words with specific letter
# Using list comprehension + len() + split()
  
# initializing string
test_str = 'geeksforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing letter 
letter = "e"
  
# extracting desired count using len()
# list comprehension is used as shorthand
res = len([ele for ele in test_str.split() if letter in ele])
  
# printing result 
print("Words count : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Count of Words with specific letter
# Using filter() + lambda + len() + split()
  
# initializing string
test_str = 'geeksforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing letter 
letter = "e"
  
# extracting desired count using len()
# filter() used to check for letter existence
res = len(list(filter(lambda ele : letter in ele, test_str.split())))
  
# printing result 
print("Words count : " + str(res))


输出
The original string is : geeksforgeeks is best for geeks
Words count : 3

方法 #2:使用 filter() + lambda + len() + split()

这是可以执行此任务的另一种方式。在此,我们使用 filter() + lambda 执行过滤任务。

蟒蛇3

# Python3 code to demonstrate working of 
# Count of Words with specific letter
# Using filter() + lambda + len() + split()
  
# initializing string
test_str = 'geeksforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing letter 
letter = "e"
  
# extracting desired count using len()
# filter() used to check for letter existence
res = len(list(filter(lambda ele : letter in ele, test_str.split())))
  
# printing result 
print("Words count : " + str(res)) 
输出
The original string is : geeksforgeeks is best for geeks
Words count : 3