[英]Counting syllables in a list of strings Python without using RE
我必須計算文本文件中的音節數。 我的問題是我不知道如何迭代每個字符串的每個字符。 我的想法是檢查一個字母是否是元音字母,如果后面的字母不是元音字母,則將計數增加 1。但我不能增加“字母”。 我也試過使用“范圍”方法,但我也有問題。 我可以嘗試什么? 謝謝你。 PS:我只能使用Python內置方法。
txt = ['countingwords', '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
你可以試試這個:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.