NLU업무중에 문장조합을 만들어야 하는 경우가 많은데.. 이게 상당히 노가다인지라 파이썬으로 허접하게 스크립트를 짜서 업무를 했었다. 물론 생각대로 안되는 부분이 많아서 조금 결과물에 손을 많이 봐야 했었지만.. 나중에 제대로 고치긴 해야한다.
아래는 사용방법
1.실행방법
1)cmd 창을 연다
2)파이썬 3버전으로 실행한다
py -3 make_sentence.py [대표발화조합목록텍스트파일] [옵션리스트텍스트파일]
예)py -3 make_sentence.py washer_tc washer_option
3)실행하면 대표발화조합목록텍스트파일_after.txt라는 이름으로 아웃풋파일이 생긴다.
2.대표발화 조합목록 텍스트파일 예시
(Washer) {Please/Try to/Attempt to/Can you/Will you} (turn off/finish/stop/end/halt) %addtional option%
각 구분은 탭으로 되어있어야 함.
{Please /Try to /Attempt to /Can you/Will you} 괄호 안의 앞뒤 띄어쓰기는 없애주는게 좋음. -> {Please/Try to/Attempt to/Can you/Will you}
%%로 되어있는 부분은 옵션리스트텍스트파일에서 읽어오게 되있음
3.옵션리스트텍스트파일 예시
%addtional option%
Turbo wash/Pre wash/Medic Rinse/Crease care/Auto Detergent/Auto Softener
%Temp option%
Cold/20 degrees/30 degrees/40 degrees/60 degrees/95 degrees
%옵션이름1%
옵션1에들어갈단어들(NE라 생각하면 됨)
%옵션이름2%
옵션2에들어갈단어들
옵션이름이 중복되면 안됨. 옵션이름은 대표발화 조합목록 텍스트 파일에 있는 %%와 이름이 똑같아야 알아서 넣어줌.
*대강 만든거라 허술한점이 많습니다. 피드백주면 추후 수정하겠습니다.
이게 실제코드
import sys
def main(argv):
input_file_name = argv[1]
option_file_name = argv[2]
output_file_name = argv[1]+'_after.txt'
input_file = open(input_file_name+".txt",'r', encoding='UTF8')
option_file = open(option_file_name+".txt",'r', encoding='UTF8')
output_file = open(output_file_name,'w', encoding='UTF8')
#조합된 문장들을 넣을 리스트.
sentences = []
#option 자료구조 형태 dic = {옵션명1:(옵션리스트...),옵션명2:(옵션리스트...),....n}
option_dic = {}
lines = option_file.readlines()
#lines = option_file.read().split()
index = 0
option_name = ''
for line in lines:
#%로 시작하면 옵션명이므로 %를 빼주고 딕셔너리의 키값으로 넣어준다.
if line.find('%') == 0:
#옵션명을 뽑아준다.
option_name = line.rstrip('\n')
else:
#/로 옵션명들을 나누어준뒤
option_list = line.rstrip('\n').split('/')
#사전에 키/밸류 넣어준다.
option_dic[option_name]=option_list
option_file.close()
#print(option_dic)
#words_list 자료구조 words = ((words1,words2,...),(words1,words2,....),(....),....n)
#() 안에 있는 것들은 없어도 됨.
#{} 안에 있는 것들은 무조건 하나씩 있어야함.
#%로 시작하는 것들은 option_file에서 읽어와야 함.
lines = input_file.readlines()
#lines = input_file.read().split()
for line in lines:
words_list = []
line_list = line.split('\t')
for data in line_list:
words=[]
if data.find('(') == 0:
#()안에 있는 경우
words.append('')
wordsInLine = data[1:len(data)-1].split('/')
for word in wordsInLine:
words.append(word)
words_list.append(words)
elif data.find('{') == 0:
wordsInLine = data[1:len(data)-2].split('/')
for word in wordsInLine:
words.append(word)
words_list.append(words)
elif data.find('%') == 0:
options = option_dic.get(data.rstrip('\n'))
for option in options:
words.append(option)
words_list.append(words)
else:
words.append(data)
words_list.append(words)
#실질적으로 문장을 만드는 부분.
sentence=''
makeSentence(words_list,sentence,0,sentences)
for sentence in sentences:
if str(sentence) != 'None':
output_file.write(str(sentence)+'\n')
#print('result : ')
#print(sentences)
#print(words_list[0])
#print(words_list[1])
#print(words_list[2])
#print(words_list[3])
#print(words_list[4])
input_file.close()
#재귀함수로 sentence 생성
#단어들집합, 현재 생성된 문장, 탐색할 인덱스값.
def makeSentence(words_list,sentence,index,sentences):
#기저조건
if index == len(words_list):
return sentence
words=words_list[index]
index=index+1
oriSentence=sentence
for word in words:
if word != '':
sentence=oriSentence+word+' '
sentences.append(makeSentence(words_list,sentence,index,sentences))
if __name__ == '__main__':
main(sys.argv)
확실히 간단하게 스크립트 짜서 사용하기엔 파이썬이 좋다!
'프로그래밍공부 > 파이썬' 카테고리의 다른 글
공공데이터 api를 이용해서 코로나 현황 웹페이지에 띄우기 (4) | 2020.09.04 |
---|---|
공공데이터api로 코로나 감염자수 증감률 확인해보기 (0) | 2020.09.03 |
토이프로젝트 (0) | 2020.08.21 |
코퍼스중복제거툴 (0) | 2020.06.30 |
코퍼스 검색툴 (0) | 2020.06.30 |