使用python查找文本文件中的字数

2024-09-22 16:38:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为content_data的文本文件,其内容如下

A house is house that must be beautiful house and never regrets the regrets for the baloon in 
the baloons. Find the words that must be the repeated words in the file of house and ballons
  1. 现在我需要使用python读取文件,并需要找到每个单词的计数
  2. 我们需要以如下格式的字典形式实现结果

    {'house':4,'baloon':3,'in':4........},

    我的意思是{word:count}

谁能告诉我怎么做吗


Tags: andthein内容datathatisbe
1条回答
网友
1楼 · 发布于 2024-09-22 16:38:39
from collections import Counter
from string import punctuation

counter = Counter()
with open('/tmp/content_data') as f:
  for line in f:
    counter.update(word.strip(punctuation) for word in line.split())

result = dict(counter)

# note: because we have
#   isinstance(counter, dict)
# you may as well leave the result as a Counter object

print result

相关问题 更多 >