2013-12-15 2 views
0

내 프로젝트는 꽤 기본 ... gettysburg 주소의 텍스트 파일을 가져와 단어 수와 고유 단어 수를 계산해야합니다. 나는 끝까지 모든 것을 끝내었지만, 대문자 첫 글자와 똑같은 이중 계산 단어들 - 즉 But와 but. 그들을 수집하는 동안파이썬 - 대문자와 소문자로 된 목록을 모두 소문자로 변경해야합니다.

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

누군가 멋진 유니 코드 조판을 사용했다면'.lower()'대신'.casefold()'를 사용할 수 있습니다. – jfs

관련 문제