Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

นับและแสดงสระในสตริงใน Python


จากสตริงของอักขระ เรามาวิเคราะห์ว่ามีอักขระกี่ตัวที่เป็นสระ

พร้อมชุด

ขั้นแรกเราจะค้นหาอักขระแต่ละตัวและที่ไม่ซ้ำกันทั้งหมด จากนั้นทดสอบว่ามีอยู่ในสตริงที่เป็นตัวแทนของสระหรือไม่

ตัวอย่าง

stringA = "Tutorialspoint is best"
print("Given String: \n",stringA)
vowels = "AaEeIiOoUu"
# Get vowels
res = set([each for each in stringA if each in vowels])
print("The vlowels present in the string:\n ",res)

ผลลัพธ์

การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -

Given String:
Tutorialspoint is best
The vlowels present in the string:
{'e', 'i', 'a', 'o', 'u'}

ด้วย fromkeys

ฟังก์ชันนี้ช่วยให้สามารถแยกเสียงสระจากสตริงโดยถือว่าเป็นพจนานุกรม

ตัวอย่าง

stringA = "Tutorialspoint is best"
#ignore cases
stringA = stringA.casefold()
vowels = "aeiou"
def vowel_count(string, vowels):

   # Take dictionary key as a vowel
   count = {}.fromkeys(vowels, 0)

   # To count the vowels
   for v in string:
      if v in count:
   # Increasing count for each occurence
      count[v] += 1
   return count
print("Given String: \n", stringA)
print ("The count of vlowels in the string:\n ",vowel_count(stringA, vowels))

ผลลัพธ์

การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -

Given String:
tutorialspoint is best
The count of vlowels in the string:
{'a': 1, 'e': 1, 'i': 3, 'o': 2, 'u': 1}