gpt4 book ai didi

python - 计算文件中所有单词的平均单词长度?

转载 作者:太空宇宙 更新时间:2023-11-03 13:46:03 25 4
gpt4 key购买 nike

所以我需要编写一个程序来计算文件中所有单词的平均单词长度。到目前为止,我已经有了这个,但我完全迷失了

newfile=input('Enter file name: ')
f=open(newfile,'r')
count1=0
count2=0
for line in f:
count1+=1
words=line.rstrip().split()
for word in words:
count2+=1
average=count1/count2
print('Average words per line: ',average)

最佳答案

wi = 词的长度 i

wavg = ∑ wi/N

with open(input('Enter file name: '),'r') as f:
w = [len(word) for line in f for word in line.rstrip().split(" ")]
w_avg = sum(w)/len(w)

关于python - 计算文件中所有单词的平均单词长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20434865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com