【发布时间】:2020-10-23 02:37:29
【问题描述】:
我正在尝试创建一个函数来计算任何给定句子中的单词数和单词的平均长度。假设句子有句号并结束句子,我似乎无法将字符串分成两个句子放入列表中。
- 问号和感叹号应替换为句点,以被识别为列表中的新句子。
- 例如:
"Haven't you eaten 8 oranges today? I don't know if you did."将是:["Haven't you eaten 8 oranges today", "I don't know if you did"] - 此示例的平均长度为 44/12 = 3.6
def word_length_list(text):
text = text.replace('--',' ')
for p in string.punctuation + "‘’”“":
text = text.replace(p,'')
text = text.lower()
words = text.split(".")
word_length = []
print(words)
for i in words:
count = 0
for j in i:
count = count + 1
word_length.append(count)
return(word_length)
testing1 = word_length_list("Haven't you eaten 8 oranges today? I don't know if you did.")
print(sum(testing1)/len(testing1))
【问题讨论】:
-
你应该用句号代替问号,而不是什么!
text = text.replace(p,'')错了
标签: python