誰能發現這個問題?每次我的索引都為負數,所以它總是打印“Before Grade 1”。我嘗試做一些正則表達式,但我仍然不知道如何真正實現它import refrom cs50 import get_stringwords = 1letters = 0sentences = 0st = get_string("Text: ")t = len(st)regex = r'\w+'output = re.findall(regex,st)for i in range(t): if st.isalpha(): letters += 1 if st.isspace(): words += 1 if st[i] == '.' or st[i] == '!' or st[i] == '?': sentences += 1L = (letters / words * 100)S = (sentences / words * 100)index = 0.0588 * L - 0.296 * S - 15.8roundedIndex = round(index)if roundedIndex < 1: print("Before Grade 1")if roundedIndex >= 16: print("Grade 16+")else: print(roundedIndex)
1 回答

慕妹3146593
TA貢獻1820條經驗 獲得超9個贊
在您的循環中,您正在檢查整個字符串是按字母順序排列還是空格,而不是與索引對應的字母是否i是。你可能想要st[i].isalpha()和st[i].isspace().
或者,您可以直接遍歷字符,而不是遍歷索引:
for char in st:
if char.isalpha():
...
if char.isspace():
...
添加回答
舉報
0/150
提交
取消