这里是python的新手。我正在尝试编写一个程序来计算句子中的平均单词长度,我必须使用.split命令来完成。顺便说一句,使用python 3.2
这是我到目前为止所写的内容
sentence = input("Please enter a sentence: ")
print(sentence.split())
到目前为止,我让用户输入一个句子并成功分割每个单词 他们进入,例如:你好我的名字是Bob,它把它分成['hi','my','name','is','bob']
但现在我迷失了,我不知道如何计算每个单词并找到句子的平均长度。
答案 0 :(得分:13)
在Python 3中(您似乎正在使用):
>>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> average = sum(len(word) for word in words) / len(words)
>>> average
2.6
答案 1 :(得分:5)
您可能希望过滤掉标点符号以及零长度字词。
>>> sentence = input("Please enter a sentence: ")
过滤掉不计数的标点符号。如果需要,可以在标点符号字符串中添加更多内容:
>>> filtered = ''.join(filter(lambda x: x not in '".,;!-', sentence))
分成单词,删除零长度的单词:
>>> words = [word for word in filtered.split() if word]
计算:
>>> avg = sum(map(len, words))/len(words)
>>> print(avg)
3.923076923076923
答案 2 :(得分:4)
>>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> sum(map(len, words))/len(words)
2.6
答案 3 :(得分:1)
简洁版:
average = lambda lst: sum(lst)/len(lst) #average = sum of numbers in list / count of numbers in list
avg = average([len(word) for word in sentence.split()]) #generate a list of lengths of words, and calculate average
分步版:
def average(numbers):
return sum(numbers)/len(numbers)
sentence = input("Please enter a sentence: ")
words = sentence.split()
lengths = [len(word) for word in words]
print 'Average length:', average(lengths)
输出:
>>>
Please enter a sentence: Hey, what's up?
Average length: 4
答案 4 :(得分:0)
def main():
sentence = input('Enter the sentence: ')
SumAccum = 0
for ch in sentence.split():
character = len(ch)
SumAccum = SumAccum + character
average = (SumAccum) / (len(sentence.split()))
print(average)
答案 5 :(得分:0)
def averageWordLength(mystring):
tempcount = 0
count = 1
wordcount = 0
try:
for character in mystring:
if character == " ":
tempcount +=1
if tempcount ==1:
count +=1
else:
tempcount = 0
try:
if character.isalpha(): #sorry for using the .isalpha
wordcount += 1
except:
wordcount = wordcount + 0
if mystring[0] == " " or mystring.endswith(" "): #i'm sorry for using the .endswith
count -=1
try:
result = wordcount/count
if result == 0:
result = "No words"
return result
else:
return result
except ZeroDivisionError:
error = "No words"
return error
except Exception:
error = "Not a string"
return error
mystring =“你有什么大空间!” 输出是3.0,我没有使用拆分
答案 6 :(得分:0)
作为模块化:
import re
def avg_word_len(s):
words = s.split(' ') # presuming words split by ' '. be watchful about '.' and '?' below
words = [re.sub(r'[^\w\s]','',w) for w in words] # re sub '[^\w\s]' to remove punctuations first
return sum(len(w) for w in words)/float(len(words)) # then calculate the avg, dont forget to render answer as a float
if __name__ == "__main__":
s = raw_input("Enter a sentence")
print avg_word_len(s)
答案 7 :(得分:0)
s = input("Please enter a sentence: ")
avg_word_len = len(s.replace(' ',''))/len(s.split())
print('Word average =', avg_word_len)
输出:
Please enter a sentence: this is a testing string
Word average = 4.0
注意:这是一个普通的用例,可以根据需要应用其他边界条件。
答案 8 :(得分:-1)
def average():
value = input("Enter the sentence:")
sum = 0
storage = 0
average = 0
for i in range (len(value)):
sum = sum + 1
storage = sum
average = average+storage
print (f"the average is :{average/len(value)}")
return average/len(value)
average()