mytext = """It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to heaven, we were all going direct the other way - in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.""" #1 mytext는문자열(string) 타입의 객체. # 여러 줄에 걸쳐있는 하나의 문자열은 """로 시작하고 마감. print(mytext) #2 mytext의 내용을 쉘(shell)에 출력. print(len(mytext)) #3 이 텍스트는 몇글자나 될까? # len()은 mytext의 길이를 리턴. 여기서 길이는 스페이스, 부호 다 포함한 글자 수. mytext2 = mytext.lower() #4 .lower()는 mytext의 대문자를 전부 소문자화. # 이렇게 소문자화된 결과를 새로운 변수(variable) 이름에 할당. print(mytext) #5 소문자화된 결과 확인. 세군데가 변했다. mytext2 = mytext2.replace('-', '') #6 대쉬('-')를 빈 문자열('')과 치환 --> 대쉬를 없애는 효과. # 치환된 결과를 다시 mytext2에 덮어씀. print(mytext2) #7 결과 확인. 하나 있던 대쉬가 사라짐. mytext2 = mytext2.replace('.', '').replace(',', '') #8 치환을 두번 겹쳐 실행함으로써 마침표와 쉼표를 없앰. # 결과를 또 다시 mytext2로 저장. print(mytext2) #9 결과 확인. 이제 모든 글자는 소문자, 대쉬, 마침표 쉼표는 다 소거. mywords = mytext2.split() #10 .split()으로 하나의 긴 문자열이었던 mytext2를 단어들의 리스트로 토큰화. # 결과는 mywords로 저장. print(mywords) #11 토큰화한 결과는 단어들의 리스트. # 리스트 타입은 [ ]로 표시되고, 각각의 구성원은 문자열 타입으로 쉼표로 분리. print(len(mywords)) #12 이 텍스트는 몇 단어로 이루어져 있을까? # len()은 mywords의 길이를 리턴. 여기서 길이는 리스트 구성원의 갯수. print(mywords.count('the')) #13 'the'는 몇번이나 사용됐을까? # .count(x)는 리스트에 적용했을 때 x의 출현 빈도를 리턴한다. myunique = set(mywords) #14 사용된 단어의 종류는 얼마나? # set()을 사용해서 리스트를 집합화, 중복 구성원을 없앤다. print(myunique) #15 사용된 단어들의 집합. # 셋(집합) 타입은 { }로 표시되고, 각각의 구성원은 문자열 타입으로 쉼표로 분리. for w in myunique : if len(w) >=10 : print(w, len(w)) #16 길이가 10글자 이상 되는 긴 단어는 뭐가 있나? # 반복문 (for-loop) 구문을 사용해서 각 단어 하나 하나(여기서는 변수 w)를 체크, # 길이가 10 이상이면 단어와 그 길이를 출력. # 각 줄은 콜론(:)으로 마쳐지고, 그 다음 줄은 4칸이 자동으로 들여써짐으로써 # 영역 (scope) 관계가 표시된다. ############################################################# #17 현재까지를 응용해 텍스트의 전반적인 정보를 요약 출력해 보자. print() print("텍스트 원문:") print(mytext) print() print("총 글자 수는", len(mytext)) print("총 단어 수는", len(mywords)) print("총 단어 가짓수는", len(myunique)) print("'the'의 출현 빈도는", mywords.count('the')) print("'it'의 출현 빈도는", mywords.count('it'))