每日一程-20.统计文本中的非重复单词

Author: Notus(hehe_xiao@qq.com)
Create: 2019-02-27
Update: 2019-02-27

统计文本中的非重复单词,并计数

环境

Python version: 3.7.1

代码如下(a.py)

'''
	统计文本中的非重复单词,并计数
	@Author: Notus(hehe_xiao@qq.com)
	@Create: 2019-02-27
	@Update: 2019-02-27
	@Version: 0.1
'''

def makewordlist(gFile):
	'''返回文件中的单词列表'''
	speech = []
	for lineString in gFile:
		wordlist = lineString.split()
		for word in wordlist:
			word = word.lower()
			word = word.strip(',.()-"\':;<> ')
			speech.append(word)
	return speech

def makeunique(words):
	'''去掉重复的词'''
	unique = []
	for word in words:
		if word not in unique:
			unique.append(word)
	return unique


gFile = open('a.txt', 'r')
words = makewordlist(gFile)
print('原文有 {} 个单词'.format( len(words) ) )
unique = makeunique(words)
print('去掉重复后有 {} 个单词'.format( len(unique) ))

运行结果

文本文件内容如下(a.txt)

Everett Copy
Edward Everett, the chief speaker at the Gettysburg cemetery dedication, clearly admired Lincoln's remarks and wrote to him the next day saying, "I should be glad, if I could flatter myself that I came as near to the central idea of the occasion, in two hours, as you did in two minutes." In 1864 Everett asked Lincoln for a copy of the speech to benefit Union soldiers, making it the third manuscript copy. Eventually the state of Illinois acquired it, where it's preserved at the Abraham Lincoln Presidential Library and Museum.

Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.

Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived, and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting-place for those who here gave their lives, that that nation might live. It is altogether fitting and proper that we should do this.

But, in a larger sense, we can not dedicate, we can not consecrate we can not hallow this ground. The brave men, living and dead, who struggled here, have consecrated it far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here.

It is for us, the living, rather, to be dedicated here to the unfinished work which they who fought here, have, thus far, so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us that from these honored dead we take increased devotion to that cause for which they here gave the last full measure of devotion that we here highly resolve that these dead shall not have died in vain that this nation, under God, shall have a new birth of freedom and that government of the people, by the people, for the people, shall not perish from the earth.

运行结果

C:\Users\Notus\Desktop>python a.py
原文有 364 个单词
去掉重复后有 192 个单词
posted @ 2019-02-27 22:30  Notus(Java)  阅读(533)  评论(0编辑  收藏  举报