728x90
반응형
28.회문판별과 N-gram 만들기
28.1 회문 판별하기
회문(palindrome)
순서를 거꾸로 읽어도 제대로 읽은 것과 같은 단어와 문장을 의미
- level, SOS, rotator, nurses run 등
- 회문은 유전자 염기서열 분석에서 많이 사용
- N-gram은 빅데이터 분석, 검색 엔진에서 많이 사용,
특히 구글은 책들을 스캔해서 N-gram viewer을 만들었는데 사람들의 언어 패턴을 시대별로 분석하기도 함
28.1 반복문으로 문자 검사하기
word = 'level'
is_palindrome = True
for i in range(len(word) // 2): # 회문 판별값을 저장할 변수, 초깃값은 true
if word[i] != word[-1 - i]:
is_palindrome = False
break
print(is_palindrome)
True
# 시퀀스 뒤집기로 문자 검사하기
print(word == word[::-1])
True
# 리스트와 reversed 사용하기
print(list(word) == list(reversed(word)))
True
# 문자열의 join 메서드와 reversed 사용하기
print(word == ''.join(reversed(word)))
True
28.2 N-gram 만들기
text = 'Hello'
for i in range(len(text) - 1): # 2-gram이므로 문자열의 끝에서 한 글자 앞까지만 반복함
print(text[i], text[i + 1], sep='') # 현재 문자와 그다음 문자 출력
He
el
ll
lo
text = 'this is python script'
words = text.split()
for i in range(len(words) - 1):
print(words[i], words[i + 1])
this is
is python
python script
# zip으로 2-gram 만들기
text = 'hello'
two_gram = zip(text, text[1:])
print(list(zip(text, text[1:])))
[('h', 'e'), ('e', 'l'), ('l', 'l'), ('l', 'o')]
for i in two_gram:
print(i[0], i[1], sep='')
he
el
ll
lo
text = 'this is python script'
words = text.split()
print(list(zip(words, words[1:])))
[('this', 'is'), ('is', 'python'), ('python', 'script')]
# 3-gram
text = 'hello'
print([text[i:] for i in range(3)]) # 원하는 3-gram이 나오지 않음
print(list(zip(*[text[i:] for i in range(3)])))
# zip에 리스트의 각 요소를 콤마로 구분해서 넣어주려면 리스트 앞에 *를 붙여야한다 == 언패킹(list unpacking)
==========================
['hello', 'ello', 'llo']
[('h', 'e', 'l'), ('e', 'l', 'l'), ('l', 'l', 'o')]
28.3 연습문제 : 단어 단위의 N-gram 만들기
n = int(input())
text = input()
words = text.split() # 공백을 기준으로 분리하여 words에 저장
if len(words) < n: # 입력한 숫자보다 문자의 길이가 작으면 wrong 출력
print('wrong')
else:
n_gram = zip(*[words[i:] for i in range(n)])
for i in n_gram:
print(i)
(입력)7
(입력)python is a programing language that lets you work quickly
('python', 'is', 'a', 'programing', 'language', 'that', 'lets')
('is', 'a', 'programing', 'language', 'that', 'lets', 'you')
('a', 'programing', 'language', 'that', 'lets', 'you', 'work')
('programing', 'language', 'that', 'lets', 'you', 'work', 'quickly')
- 문자열 단위의 N-gram 만들기
n = int(input())
text = input()
words = list(zip(*[text[i:] for i in range(n)]))
if len(text) < n:
print('wrong')
else:
for i in words:
print(i)
(입력)3
(입력)level
('l', 'e', 'v')
('e', 'v', 'e')
('v', 'e', 'l')
28.4 심사문제 : 파일에서 회문인 단어 출력하기
단어가 줄 단위로 저장된 words.txt 파일이 주어질 때,
words.txt 파일에서 회문인 단어를 각 줄에 출력하는 프로그램을 만들자.
단어를 출력할 때는 등장한 순서대로 출력해야 하며, 파일에서 읽은 단어는 \n이 붙어있으므로 이를 제거한 뒤 판단하고
\n이 출력되지 않도록 한다.
sample = ['apache', 'decal', 'did', 'neep', 'noon', 'refer', 'river']
with open('28.4.text', 'w') as file:
for i in sample:
file.write(i + '\n')
with open('28.4.text', 'r') as file:
lines = file.readlines();
for i in lines:
word = i.rstrip()
if list(word) == list(reversed(word)):
print(word)
did
noon
refer
728x90
반응형
'Language > Python' 카테고리의 다른 글
[코딩도장]30. 위치 인수와 키워드 인수 사용 (0) | 2022.03.25 |
---|---|
[코딩도장]29. 함수 사용 (0) | 2022.03.24 |
[코딩도장]27. 파일 사용 (0) | 2022.03.21 |
[코딩도장]26.세트사용하기 (0) | 2022.03.21 |
[코딩도장]25.딕셔너리응용 (0) | 2022.03.18 |