re
(regular expression) 모듈 사용방법
re
모듈의 compile
함수import re
m = re.match('([0-9]+) ([0-9]+)', '10 295')
print(m)
print(m.group())
print(m.group(1))
print(m.group(2))
<a href="c:\Python34\Koala.jpg">그림</a><font size = "10">
이 코드에서 그림의 경로인 c:\Python34\Koala.jpg 부문만 꺼내오고 싶다면, 어떻게 해야할까?
import re
url = '<a href="c:\Python34\Koala.jpg">그림</a><font size = "10">'
print(re.search('href="(.*?)">', url).group(1))
p = re.compile(r'(\b\w+)\s+\1') # \s (공백문자), \w (영문자+숫자), \b (단어경계)
p.search("Paris in the the spring").group() # group() (RE에 일치된 문자열을 반환)
정규식 패턴 표현
.
\n
(=newline)을 제외한 모든 문자*
앞 pattern이 0개 이상+
앞 pattern이 하나 이상이어야 함. ?
앞 pattern이 없어가 하나 (optional pattern\b
단어(word boundary)경계\w
문자(character)의미\s
공백문자(white space)를 의미 (== [\t\n\r\f])\1
backrereference로서 처음 match된 group을 지칭Seoul Corpus 등에서 vowel harmony에 관심이 있다면...
regex = re.compile('[^aeiou]')
lists = regex.split('iip0aarriissiissii') # SeoulCorpus의 전사 예
new_lists = []
for l in lists:
if l != "":
new_lists.append(l)
print(new_lists)
for l in range(len(new_lists)-1):
print("Check harmony for: ", new_lists[l], new_lists[int(l)+1])
if new_lists[l] == new_lists[l+1]: print('\t[', new_lists[l], '] [', new_lists[l+1], '] are in harmony')
else: print('\tno harmony')
re.sub()
함수는 문자열에서 매치된 텍스트를 다른 텍스트로 치환text = '즐거운 perl 프로그래밍'
pattern = re.compile(r'perl')
output = re.sub(pattern, 'Python', '즐거운 perl 프로그래밍')
print('text:', text)
print('output:', output)
(?=...)
와 (?!...)
: looka head & negative look ahead(?<=...)
와 (?<!...)
: look behind & negative look behind
[문자들 ]
가능한 문자들의 집합을 정의하며, 문자들 중의 하나면 matching
[^문자들]
가능하지 않는 문자들의 집합, 이 문자들이 아니면 matching# look ahead and look forward
import re
place = re.compile('(?<=m)[^pbmw]')
m = re.search(place, 'amta')
if m:
print('[', m.group(), '] occurs after [m], which violates place assimilation')
else: print('찾는 문자열이 없습니다.')
단어 발음
의 순으로 발음사전이 구성되어 있다는 것을 알 수 있다. %ls data/*
eng_dict = open('data/english_dict.txt', "r")
lines = eng_dict.readlines()
eng_dict.close()
print(lines[:10])
eng_dict = {}
for line in lines:
line = line.strip().split('\t')
ortho = line[0]
pron = line[1]
#print(ortho, pron)
eng_dict[ortho] = pron
word = input('Type a word to check the pronunciation:')
print(eng_dict.get(word, 'N/A'))
#define vowels
vowels = 'aeiouɜɛɑʊ'
#get the word from the user
word = input("Type a word: ")
#proceed as before...
eng_dict = {}
for line in lines:
line = line.strip().split()
ortho = line[0]
pron = line[1]
#print(ortho, pron)
eng_dict[ortho] = pron
word = eng_dict.get(word, 'N/A')
counter = 0
vowelcount = 0
while counter < len(word):
if word[counter] in vowels:
vowelcount += 1
counter += 1
else:
print('There are',vowelcount, 'vowels in this word: ', word)
print(" NOTE: The diphthongs are not treated properly. I will leave this as a work to do")
glob()
함수는 복잡한 정규표현식이 아닌, 유닉스 쉘 규칙을 사용하여 일치하는 파일(file)이나 디렉토리(directory)의 이름을 검색한다. 규칙은 다음과 같다:
*
(re 모듈에서 .*
와 같다)?
[abc]
[!abc]
import glob
files = glob.glob('data/*.txt')
for file in files:
print(file)
files = glob.glob('data/Seoul*[234]*.txt')
for file in files:
print(file)
! head data/SeoulCorpus4PCT_s02_results.txt
# Error will occur
for file in files:
print(file)
fin = open(file, 'r')
lines = fin.readlines()
fin.close()
for line in lines:
line = line.strip().split()
print(line)
import sys
sys.getdefaultencoding()
import io, re
fout = open('data/test.txt', 'w')
for file in files:
print(file)
fin = io.open(file, 'r', encoding="utf-16")
lines = fin.readlines()
fin.close()
fout.close()
vowels = 'aeiou'
word = 'sthetic'
counter = 0 # 문자 수를 세기 위하여
cluster=[] # 빈 리스트에 모음을 만나기 전까지의 자음들을 저장하기
for i in range(len(word)): # 단어의 개수까지를 레인지로 잡아서
if word[i] in vowels:
break
cluster.append(word[i])
counter += 1
cluster_string = ''.join(cluster)
print("The word begins with", counter, "consonant letters")
print("The consonant letters are [", cluster_string, "]")
print(range(7))
word_dict = {'a': 100, 'b': 0.00000001}
total_freq = sum(word_dict.values())
print(total_freq)
from math import log2
def entropy(word, freq):
h = -(freq/total_freq)*log2(freq/total_freq)
return (word, h)
total_H= []
for wrd, freq in word_dict.items():
total_H.append(entropy(wrd, freq)[1])
print(entropy(wrd, freq))
print(total_H)
print("Total Entropy is: ", sum(total_H))
# open the file
fin = open('data/alice.txt', 'r')
# read it all in
text = fin.read()
# close the file stream
fin.close()
# convert to lowercase and split into words
words = text.lower().split()
print(words[:50])
words_str = ' '.join(words)
import re
# punctuation
punct = re.compile('[\.\?\-!\*,"\(\):\'\[\];_/~]')
new_words = re.sub(punct, ' ', words_str)
new_words_list = new_words.split()
print(new_words_list[:50])
worddict = {}
for w in new_words_list:
if w in worddict:
worddict[w] += 1
else:
worddict[w] = 1
for wrd, freq in sorted(worddict.items(), key=lambda t : t[1], reverse=True):
print(wrd, '\t', freq)
# lambda 함수에 t와 t[1]을 사용하였는데,
# 여기에서 t는 worddict.items()에서 얻은 목록에 들어 있는 항목을 의미하며,
# t 항목은 ('key', value) 튜플로 되어 있습니다.
# 그렇기 때문에 t[1]은 value를 의미하여 정렬하는 키를 value로 하라는 의미입니다
total_freq = sum(worddict.values())
from math import log2
def word_entropy(word, freq):
h = -(freq/total_freq)*log2(freq/total_freq)
return (word, h)
total_H= []
for wrd, freq in sorted(worddict.items(), key=lambda t : t[1], reverse=True):
total_H.append(word_entropy(wrd, freq)[1])
print(word_entropy(wrd, freq)[0], '\t', word_entropy(wrd, freq)[1], '\t', freq)
print("Total Entropy is: ", sum(total_H))
clusters = []
for w in new_words_list:
m = re.search('^[^aeiou]*', w)
if m:
onset = w[0:m.end()]
clusters.append(onset)
print(clusters[:40])
# eliminate duplicate onsets
clusters = sorted(set(clusters))
print(clusters)
# Refinement
# words that contain a vowel and that have non-word-initial y
clusters = []
for w in words:
m = re.search('^([^aeiouy]*)[aeiouy]', w)
if m:
if m.end(1) == 0 and w[0] == 'y':
onset = 'y'
else:
onset = w[0:m.end(1)]
clusters.append(onset)
# eliminate duplicate onsets
clusters = sorted(set(clusters))
print(clusters)
# count all clusters
clusters = {}
for w in words:
m = re.search('^([^aeiouy]*)[aeiouy]', w)
if m:
if m.end(1) == 0 and w[0] == 'y':
onset = 'y'
else:
onset = w[0:m.end(1)]
if onset in clusters:
clusters[onset] = clusters[onset] + 1
else:
clusters[onset] = 1
# print onset counts
keys = sorted(clusters.keys())
for c in keys:
print(c, ":", clusters[c], sep="")