การนับพยางค์ในรายการสตริง Python โดยไม่ต้องใช้ RE

Nov 15 2020

ฉันต้องนับจำนวนพยางค์ในไฟล์ข้อความ ปัญหาของฉันคือฉันไม่รู้ว่าจะวนซ้ำอักขระแต่ละตัวของแต่ละสตริงอย่างไร ความคิดของฉันคือตรวจสอบว่าตัวอักษรเป็นสระหรือไม่และถ้าตัวอักษรต่อไปนี้ไม่ใช่สระให้เพิ่มจำนวนทีละ 1 แต่ฉันไม่สามารถเพิ่ม "ตัวอักษร" ได้ ฉันพยายามใช้เมธอด "range" ด้วย แต่ฉันก็มีปัญหาเช่นกัน ฉันจะลองทำอะไรได้บ้าง? ขอขอบคุณ. PS: ฉันสามารถใช้วิธีการในตัวของ Python เท่านั้น

txt = ['countwords', 'house', 'plant', 'alpha', 'syllables']

นี่คือรหัสของฉันจนถึงตอนนี้

def syllables(text_file):

    count = 0
    vowels = ['a','e','i','o','u','y']

    with open(text_file, 'r') as f:
   
    txt = f.readlines()
    txt = [line.replace(' ','') for line in txt]
    txt = [line.replace(',','') for line in txt]
    txt = [y.lower() for y in txt]

        for word in txt:
            for letter in word:
                if letter is in vowel and [letter + 1] is not in vowel:
                    count += 1
   

คำตอบ

cknoll Nov 14 2020 at 23:32

คุณอาจลองทำสิ่งนี้:

lines = ["You should count me too"]
count = 0
vowels = "aeiouy"

for line in lines:
    for word in line.lower().split(" "):
        for i in range(len(word)):
            if word[i] in vowels and (i == 0 or word[i-1] not in vowels):
                count +=1
print(count) # -> 5