강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

레오님의 프로필 이미지
레오

작성한 질문수

프로그래밍, 데이터 과학을 위한 파이썬 입문

File Handling1

수업 과제(?) 제출

작성

·

129

0

import string

with open("i_have_a_dream.txt", "r") as my_file:
    contents = my_file.read()  # 파일 읽기

    contents = contents.lower()  # 소문자로 변환

    remove_this_set = set(string.punctuation)  # 문장부호 집합
    contents = ''.join([ch for ch in contents if ch not in remove_this_set])  # 문장부호 삭제

    word_list = list(set(contents.lower().split()))    # 단어 리스트 추출

    line_list = contents.splitlines()  # 줄 리스트 추출
    line_list = [line for line in line_list if line is not '']  # 빈 줄 삭제

print("Total Number of Characters :", len(contents))
print("Total Number of Words:", len(word_list))
print("Total Number of Lines :", len(line_list))

# before
# Total Number of Characters : 9198
# Total Number of Words: 1656
# Total Number of Lines : 87

# after
# Total Number of Characters : 8991
# Total Number of Words: 536
# Total Number of Lines : 44

제출한 코드 (아래)를
''.join([ch for ch in contents if ch not in remove_this_set])

이렇게 바꾸어도 잘 동작하더라구요
''.join(ch for ch in contents if ch not in remove_this_set)

이게 generator랑 iteration과 관련이 있나요?

참조:
stackoverflows 질문&답변
python3 docs의 str.strip()
python3 docs의 str.punctuation()

답변

답변을 기다리고 있는 질문이에요
첫번째 답변을 남겨보세요!
레오님의 프로필 이미지
레오

작성한 질문수

질문하기