สร้างโปรแกรมแปลภาษาด้วย PyThaiNLP

ด้วยความสามารถทางด้านการประมวลผลภาษาธรรมชาติที่ PyThaiNLP มีอยู่ คุณสามารถสร้างโปรแกรมแปลภาษาด้วย Python ได้อย่างง่ายดาย

ติดตั้ง PyThaiNLP

pip install pythainlp

ตัวอย่างโค้ดแบบง่ายๆ:

from pythainlp.translate import Translate

th2en = Translate('en', 'th')
en2th = Translate('th', 'en')

# ตัวอย่างการใช้งาน
english_text = "Hello, how are you?"
thai_text = "สวัสดีครับ สบายดีไหมครับ"

translated_english = en2th.translate(english_text)
translated_thai = th2en.translate(thai_text)

print(translated_english)
print(translated_thai)

ในตัวอย่างนี้ เราใช้ Translate จาก PyThaiNLP เพื่อแปลข้อความระหว่างภาษาอังกฤษและภาษาไทย โดยกำหนดภาษาต้นทางและภาษาปลายทาง โดย src และ dest ตามลำดับ

คุณสามารถปรับแปลงและประยุกต์ใช้โปรแกรมนี้ตามความต้องการของคุณ เช่น แปลภาษาในไฟล์หรือแปลภาษาในข้อความที่รับเข้ามาผ่านอินพุต

หวังว่าคำแนะนำนี้จะเป็นประโยชน์และช่วยให้คุณสร้างโปรแกรมแปลภาษาด้วย PyThaiNLP ได้ครับ! 🚀

ตัวอย่างโค้ดการแปลไฟล์ Json และบันทึกกลับเป็นไฟล์ Json อีกครั้ง:

from pythainlp.translate import Translate
import json
th2en = Translate('en', 'th')

with open("/content/th.json", "r") as file:
    data = json.load(file)

translated_data = {}
for key, value in data.items():
    if isinstance(value, str):
        translated_value = th2en.translate(value)
        translated_data[key] = translated_value
    else:
        translated_data[key] = value

with open('/content/output.json', 'w', encoding='utf8') as file:
    json.dump(translated_data, file, ensure_ascii=False)