[英]Using a Text file to count certain words in PYTHON
我需要很多幫助。 我正在嘗試使用文本文件僅計算文本中的某些單詞。 我一直在尋找幾個小時來嘗試尋求幫助,但似乎找不到任何幫助。
需要變得敏感我需要使用的詞是:偉大的、好的、完美的、漂亮的、美妙的、愛的、愛的、快樂的、享受的、美妙的
您可以使用“re.findall”或“re.finditer”等正則表達式來搜索單詞,然后遍歷整個文件。
list = []
with open("file.txt") as f:
words = f.read()
list.append(re.findall(r"great", words))
然后你可以通過len函數來統計單詞。 根據要求,代碼可能需要稍作修改。 瀏覽正則表達式頁面以獲取更多信息。
你甚至可以使用 str.count()。
collections.Counter
提供了許多計算單詞的選項
from collections import Counter
with open('alice.txt') as f:
content = f.read()
c = Counter(content.split())
print(c['you'])
lst = ['me', 'them', 'us']
for i in lst:
print(f'{i}: {c[i]}')
for word, count in c.most_common(5):
print(word + ':', count)
301 me: 46 them: 49 us: 10 the: 1664 and: 780 to: 773 a: 662 of: 596
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.