Django

Django 추출단어 랜덤

OnejinSim 2023. 11. 16. 15:58

사용자로부터 이미지를 입력을 받았고 받은 이미지로부터 단어를 추출하는데 성공하였다.

이제는 단어를 섞어주어야한다.

단어를 섞어주는 기능을 할 함수가 필요한데 이를 장고의 html파일이 아니라 views.py에 만들어 줄것이다.

우선 버튼을 만들어주자. orc.html 파일에 

<a href="{% url 'pybo:shuffle' %}" class="btn btn-primary">단어섞기</a>

처럼 버튼을 만들어주고 url.py에

path('ocr/', base_views.shuffle, name='shuffle'),

로 views로 넘겨준다. base_views.py에는 

def shuffle(request):
    # 리스트의 순서를 랜덤하게 섞음
    random.shuffle(texts)

    # 템플릿으로 데이터 전달
    context = {'texts': texts, 'image':new_image_path}
    return render(request, 'pybo/ocr.html', context)

 

를 준다. 

이때 texts 나 new_image_path 같은 것은 활용된 함수 내에서 글로벌로 선언해 주었다.

def ocrTest(request, question_id):
    global texts, new_image_path
    ...

 

++++++

업데이트

++++++

위 코드는 일본어 단어의 순서만을 바꾸는데 번역된 한글까지 같이 섞어주는 코드는 아래와 같다.

def shuffle(request):
    # 리스트의 순서를 랜덤하게 섞음
    # random.shuffle(texts)
    random.shuffle(combined_list)
    shuffled_texts, shuffled_trans = zip(*combined_list)
    # 템플릿으로 데이터 전달
    # context = {'texts': shuffled_texts, 'trans': shuffled_trans}
    context = {'combined_list': combined_list}
    return render(request, 'pybo/ocr_lists.html', context)

버튼을 누를때마다 단어의 순서가 섞이도록 했으니 이제 화면에 출력해주자.

<table border="1px">
    <tr><td colspan="3" style="border: none;"><a href="{% url 'pybo:shuffle' %}" style="width: 100%" class="btn btn-primary float-right">단어섞기</a></td>
    <tr><th style="col-1">번호</th><th style="width: 45%">일본어</th><th style="width: 45%">한국어</th></tr>
        {% if combined_list %}
        {% for text, translation in combined_list %}
    <tr>
        <td>
            {{ forloop.counter }}
        </td>
        <td>
            {{text}}
        </td>
        <td>
            {{ translation }}
        </td>
    </tr>
    {% endfor %}
        {% endif %}
</table>

combined_list는 translate 함수에서 나온다. 이 리스트에는 일본어와 한국어 단어의 순서가 매칭 되어있고

두개가 붙어있는 리스트를 파이썬에서 출력하는 방법이 

for text, translation in combined_list

인것이다.

결과값