ในบทความนี้ เราจะเรียนรู้เกี่ยวกับวิธีแก้ปัญหาและแนวทางในการแก้ปัญหาที่ระบุ
คำชี้แจงปัญหา
ได้ประโยคมาเราต้องนับจำนวนคำในประโยค
ในที่นี้เราจะพูดถึงสองแนวทาง -
วิธีที่ 1 − การใช้ฟังก์ชัน split()
ตัวอย่าง
test_string = "Tutorials point "
res = len(test_string.split())
print ("The number of words in string are : " + str(res)) ผลลัพธ์
The number of words in string are : 2
วิธีที่ 2 − การใช้ฟังก์ชัน strip() &isalpha()
ตัวอย่าง
import string
test_string = "Tutorials point "
res = sum([i.strip(string.punctuation).isalpha() for i in test_string.split()])
print ("The number of words in string are : " + str(res)) ผลลัพธ์
The number of words in string are : 2
บทสรุป
ในบทความนี้ เราได้เรียนรู้เกี่ยวกับวิธีการนับคำในประโยค