2013-12-15 25 views
0

我的項目非常基礎......我需要獲取gettysburg地址的文本文件並計算單詞數量和唯一單詞數量。我幾乎一直到最後,但它的重複計數單詞與首字母大寫相同 - 即But和But。我不知道如何解決這個問題:(這是我到目前爲止有:Python - 需要將大寫和小寫單詞換成小寫字母

def main(): 
    getty = open('Gettysburgaddress.txt','r') 
    lines = getty.readlines() 
    getty.close() 

    index = 0 
    while index < len(lines): 
     lines[index] = lines[index].rstrip('\n') 
     index += 1 

    words = [word for line in lines for word in line.split()] 

    size = len(words) 

    print('\nThere are', size,'words in the Gettysburg Address.\n') 

    unique = list(set(words)) 

    size_unique = len(unique) 

    print('There are', size_unique,'unique words in the Gettysburg Address.\n') 

    unique.sort() 

    print('Sorted order of unique words:', unique) 

    close = input('') 

main() 

回答

3

小寫的話,同時收集他們:

words = [word.lower() for line in lines for word in line.split()] 

或創建一組唯一字時:

unique = list(set(word.lower() for word in words)) 

您可以簡化您的文件加載碼多一點:

with open('Gettysburgaddress.txt','r') as getty: 
    words = [word.lower() for line in getty for word in line.split()] 

這一步將文件加載到小寫字母列表中,其中with語句還負責再次關閉文件。

+0

感謝那些工作。沒有意識到你可以早點添加下面的命令! – KwakKwak

+0

你可以使用''.casefold的(),而不是'.lower()'萬一有人二手花式統一排版。 – jfs

相關問題