def EditDistance(source, target): #source에서 target으로의 편집거리를 구하는 함수
D = [[0]*(len(target)+1) for _ in range(len(source)+1)] #2차원배열을 0으로 초기화
for i in range(len(source) + 1):
D[i][0] = i #target의 길이가 0이므로 편집거리를 0으로 초기화
for j in range(len(target) + 1):
D[0][j] = j #source의 길이가 0이므로 편집거리를 0으로 초기화
for i in range(1, len(source) + 1):
for j in range(1, len(target) + 1):
if source[i-1] == target[j-1]: #마지막 글자가 같으면 a는 0
a = 0
else: #마지막 글자가 다르면 a는 1
a = 1
D[i][j] = min(D[i][j-1] + 1, D[i-1][j] + 1, D[i-1][j-1] + a)
return D[len(source)][len(target)]
def TextTolist(Text): #Text를 단어별로 나눠서 리스트로 만드는 함수
f = open(Text, 'r', encoding='UTF8')
text = f.read()
f.close()
text = text.replace("\n", " ") # 줄바꿈을 공백으로 바꿈
text = text.replace(".", "") # .을 지워버림
TextToList = text.split(" ")
return TextToList
def ListToDic(Text_List, ED_List): #TextList와 E_D_list를 합쳐서 딕셔너리로 만드는 함수
dic = dict()
for i in range(len(Text_List)):
dic[Text_List[i]] = ED_List[i]
return dic
Target = input("단어를 입력하세요 : ")
TextList = TextTolist("text.txt")
E_D_list = []
for k in range(len(TextList)):
E_D = EditDistance(TextList[k], Target)
E_D_list.append(E_D)
E_D_Dic = ListToDic(TextList, E_D_list)
E_D_Dic = sorted(E_D_Dic.items(), key=lambda x: x[1])
for i in range(5):
print("{0}번째로 유사한 단어는 {1}이고 편집횟수는 {2}회".format(i+1, E_D_Dic[i][0], E_D_Dic[i][1]))


'Member > 홍혁진' 카테고리의 다른 글

백준 14501 퇴사  (0) 2019.11.24
백준 1463 1로만들기  (0) 2019.11.23
백준 10040 투표  (0) 2019.11.20
백준 11650 좌표정렬하기  (0) 2019.10.12
백준 1427 소트인사이드  (0) 2019.10.12

+ Recent posts