共計 536 個字符,預計需要花費 2 分鐘才能閱讀完成。
可以通過以下步驟來統計單詞的個數:
- 將文本內容分割成單詞列表
- 遍歷單詞列表,統計每個單詞的出現次數
下面是一個示例代碼,用于統計文本中單詞的個數:
def count_words(text):
# 將文本內容轉換為小寫,并去除標點符號
text = text.lower()
text = ''.join(e for e in text if e.isalnum() or e.isspace())
# 分割文本內容為單詞列表
words = text.split()
# 統計每個單詞的出現次數
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
text = "Python is a popular programming language. Python is used in various fields including web development, data science, and machine learning."
result = count_words(text)
print(result)
運行以上代碼,將輸出每個單詞及其出現的次數。
丸趣 TV 網 – 提供最優質的資源集合!
正文完