我无法转换所有字数的总和。我尝试了各种方法,每个单词的长度是正确的,我只是不能得到一个总数?
file=open(r"sheSaid.txt","r+")
from collections import Counter
wordcount = Counter(file.read().split())
for word in file.read().split(' '):
word = word.rstrip(".""',?!")
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
#print (word.rstrip(".""..',?!"),wordcount)
for item in wordcount.items(): print("{}\t{}".format(*item))
wordCount = len(wordcount)
#can count all word lengths just fine
print ("The total word count is:", word, wordCount) # when I use Len() Or #Count I cannot get the sum of all wordCounts?
print ("The total length of all words are:","total_of_all_word_counts?")
#I need the sum to complete this
print ("The avg length is:", wordcount/total_of_all_word_counts?)
file.close();
答案 0 :(得分:0)
这样的事情会有所作为,虽然不清楚你在寻找什么,但这会计算文本文件中的单词,计算所有单词的字符数,然后计算字符平均值:
file = open(r"sheSaid.txt","r+")
file_contents = file.read().split() # Reads the file and split by spaces to create a list of words
file.close() # Always good idea to close the file after done with it
words_count = len(file_contents)
characters_count = len(''.join(file_contents))
average_characters = characters_count / words_count
您可能需要付出额外的努力并处理其他一些情况,例如删除!
,.
等字符。这将是直截了当的。这只是一个建立起点的起点。您只知道角落案例以及文本文件中的内容。