任一个英文的纯文本文件,统计其中的单词出现的个数。
上网找了一下思路。首先要读取文本,对文本进行处理——这里的处理要包括去除空格及各个标点符号。处理好的文本就是一串单词,可以用list储存。接下来,就是统计list中各单词的重复次数了,最简单的想法,应该是一个个遍历,将之前未出现的录入一个dict中,出现过的增加个数。
写起来很简单。其中defaultdict
与dict
几乎一样,但可以起到设置默认值的作用,如果不存在就会设置默认值为0;也可以用条件判断解决。
唯一的难点就是如何排序,dict类型是无法排序的,所以需要借助函数sort
,sort
接收四个参数,第一个是iterable
,即可迭代参数,而dict就是iterable
值。
import re
from collections import defaultdict
if __name__ == '__main__':
w_dict = defaultdict(int)
with open('subtitle.txt', 'r') as fp:
for line in fp.readlines():
s_list = re.split(r'[\s\,\.\?\"]+', line.strip())
for w in s_list:
w_dict[w] += 1 # 不会报错,设置默认值为0
for w in sorted(w_dict, key=w_dict.get, reverse=True):
print(w, w_dict[w])
import re
from collections import defaultdict
# filter()也接收一个函数和一个序列。和map()不同的时,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
if __name__ == '__main__':
w_dict = defaultdict(int)
with open('subtitle.txt', 'r') as fp:
article = fp.read().replace('\n', ' ')
s_list = re.split(r'[\s\,\.\?\"]+', article)
s_list = [item for item in filter(lambda x: x != '', s_list)]
# 去掉空串,空串出现在最后一个逗号后面
for w in s_list:
w_dict[w] += 1
for w in sorted(w_dict, key=w_dict.get, reverse=True):
print(w, w_dict[w])
嗯,没什么好说的。。
import string
# simply extend word like: it's => it is
def extend_word(text):
if text.find('\'') > 0:
old2new = dict()
words = text.split()
for word in words:
if word.find('\'') > 0:
parts = word.split('\'')
if parts[1] == 'm':
parts[1] = 'am'
elif parts[1] == 's':
parts[1] = 'is'
elif parts[1] == 're':
parts[1] = 'are'
elif parts[1] == 't':
parts[1] = 'not'
elif parts[1] == 've':
parts[1] = 'have'
elif parts[1] == 'll':
parts[1] = 'will'
elif parts[1] == 'd':
if words[words.index(word) + 1] == 'better':
parts[1] = 'had'
else:
parts[1] = 'would'
if parts[0].endswith('n'):
parts[0] = parts[0][:-1]
old2new[word] = ' '.join(parts)
_text = text
for old_word in old2new.keys():
_text = _text.replace(old_word, old2new[old_word])
return _text
def return_order_key(record):
return record[1]
def show_in_order(records):
items = sorted(records.items(), key=return_order_key, reverse=True)
for item in items:
print(item[0], item[1])
with open('subtitle.txt', 'r') as file:
article = file.read()
no_pun_text = article
_punctuation = string.punctuation.replace('\'', '')
for pun in _punctuation:
no_pun_text = no_pun_text.replace(pun, '')
complete_text = extend_word(no_pun_text)
records = dict()
for word in complete_text.lower().split():
records[word] = records.get(word, 0) + 1
show_in_order(records)