关于python入门经典的葛底斯堡演说
def analyseFile(File):
words = []
for line in File:
lineWord = line.split()
for word in lineWord:
word.lower()
word.strip(',.')
if word != '--':
words.append(word)
return words
def makeUnique(speech):
unique = []
notUnique = []
for word in speech:
if word not in unique:
unique.append(word)
elif word in unique and word not in notUnique:
notUnique.append(word)
elif word in unique and word in notUnique:
continue
return len(unique) - len(notUnique)
gFile = open("gettysburg", 'r')
speechWords = analyseFile(gFile)
print("speech Length:", len(speechWords))
uniqueWords = makeUnique(speechWords)
print("unique length:", uniqueWords)
我觉得书中的代码并不能实现提出的目标:
追踪文件只出现一次的不同单词
我将第二个函数进行了修改,如果一个单词第一次出现进去unique,第二次出现进去notunique,之后再出现不进行处理。这样子两个列表元素之差就代表只出现一次的不同单词数量
编程的小tip
在python中的并且和或不是 && ||,而是英文单词and和or