我有一個包含100個句子的文本文件。我想寫一個python腳本,將從一個文本文件中計算平均句子長度(單詞)包含100個句子。 謝謝如何從一個文本文件中計算平均句子長度(單詞)包含使用python的100個句子
-5
A
回答
3
wordcounts = []
with open(filepath) as f:
text = f.read()
sentences = text.split('.')
for sentence in sentences:
words = sentence.split(' ')
wordcounts.append(len(words))
average_wordcount = sum(wordcounts)/len(wordcounts)
+0
非常感謝!非常感謝你的幫助。 –
0
這應該會幫助你。但這是基本的東西,你應該至少嘗試一下自己。
此代碼假定每個句子都在一個新行中。
如果不是這種情況,您可以更正代碼,也可以在您的問題中反映出這一點,但對此並不清楚。
def read_lines_from_file(file_name):
with open(file_name, 'r') as f:
for line in f:
yield line.strip()
def average_words(sentences):
counts = []
for sentence in sentences:
counts.append(sentence.split())
return float(sum(counts)/len(counts))
print average_words(read_lines_from_file(file_name))
4
相關問題
- 1. 將R用於文本文件的平均句子長度
- 2. 從java中的文本文件中提取包含2個單詞的句子
- 3. 平均單詞長度和平均句子長度的Java代碼
- 4. 計算並平均句子中的單詞
- 5. 如何計算句子中的單詞?
- 6. 如何計算一個單詞在一個句子中出現的次數? (Python)
- 7. 如何在文本框中找到最長的句子和平均句子長度?
- 8. 如何計算一個句子中的單詞數量?
- 9. 從單詞列表中將句子寫入文本文件 - python
- 10. 最長的單詞在句子長度
- 11. 從一個句子中獲取長度與單詞長度的數組-javascript
- 12. 如何從一個變量grep一個確切的單詞包含句子
- 13. 如何計算文本文件(C#)中的一個句子中的元音
- 14. 獲取句子中的單詞長度
- 15. 如何使用where子句計算mysql的平均值
- 16. Python如何計算每個詞彙單詞在句子中顯示的次數?
- 17. 的Python:計算值的平均值在一個文本文件
- 18. Python提取包含2個單詞的句子
- 19. 使用java計算文本文件中的句子
- 20. 在一個句子中計算特定單詞的出現haskell
- 21. 計算句子第一個單詞中的字母數
- 22. 使用MapReduce刪除包含特定單詞的整個句子
- 23. 讀取文本文件並計算每個第三個字的平均長度
- 24. PHP如何計算文本文件中每個單詞的長度
- 25. 如何從包含多個句子的輸入文件中查找單個單詞。 C++
- 26. 從文本文件,如何使兩個數組包含單詞
- 27. 如何刪除包含特定文本的整個句子?
- 28. 如何拼寫一個句子中的單詞 - Python
- 29. 如何在單詞中搜索句子的第一個單詞
- 30. 計數在VBA中一個句子中出現一個單詞
你的代碼是什麼樣的? – Hyperboreus
我想要的代碼。我是python的新手。無法通過網絡找到解決方案。 –