2013-12-15 23 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

相关问题