学习Python也有一周的时间,将学到的内容通过一个文本处理的小程序进行总结,需求如下:
- 分析文件长度,按单词计数
追踪文件中只出现一次的不同单词
文本采用1863年林肯先生的《葛底斯堡演说》为例。
def makeWordList(gFile):
speech = []
for lineString in gFile:
lineList = lineString.split()
for word in lineList:
word = word.lower().split(".,")
if word!="--":
speech.append(word)
return speech
def makeUnique(speech):
unique = []
for word in speech:
if word not in unique:
unique.append(word)
return unique
gFile = open("/Users/Megustas/Desktop/gettysburg.txt","rU")
speech = makeWordList(gFile)
print(speech)
print "Speech Length:",len(speech)
unique = makeUnique(speech)
print(unique)
print "Unique Length:",len(unique)
运行结果: