我是python的新手,需要幫助查找平均值,例如:每個句子的平均詞數,每個詞的平均字符數,總詞數和句子數量等。我有三個包含大量文本樣本的文本文件。這是我迄今爲止所擁有的。Python:查找平均值
sampleText1 = open("textFile1.txt")
split1 = sampleText1.split(" ")
words1 = len(split1)
這就是我所有的。我一直在想,因爲我不得不爲其他兩個文本文檔重用該代碼,所以我應該創建一個函數或類似的東西。我在Stack Overflow上找到了這個代碼posted by Inbar Rose。我是否應該同樣使用以下代碼?
def clean_up(word, punctuation="!\"',;:.-?)([]<>*#\n\\"):
return word.lower().strip(punctuation) # you don't really need ".lower()"
def average_word_length(text):
cleaned_words = [clean_up(w) for w in (w for l in text for w in l.split())]
return sum(map(len, cleaned_words))/len(cleaned_words) # Python2 use float
>>> average_word_length(['James Fennimore Cooper\n', 'Peter, Paul and Mary\n'])
我想我需要做這樣的事情。任何人都可以幫我找到這些平均值嗎?另外,如果有人知道任何學習Python的好資源,請讓我知道。我目前在Lynda.com上使用http://learnpythonthehardway.org/book/,Khan Academy Python視頻和Python上的一些視頻。
問題是什麼?你有沒有試過*使用該代碼? – jonrsharpe
縮進在Python中很重要。請更正發佈的代碼,使其有效。 – unholysampler
這不是你的問題的答案,因爲我懷疑你想寫這些方法來學習如何去做,但有一個Python自然語言處理庫,用文檔做一些非常複雜的事情。也許你會想看看它的想法:http://www.nltk.org/ – duffymo