在不使用 RE 的情况下计算字符串列表 Python 中的音节
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
我必须计算文本文件中的音节数。我的问题是我不知道如何迭代每个字符串的每个字符。我的想法是检查一个字母是否是元音字母,如果后面的字母不是元音字母,则将计数增加 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