我正在使用Python(3.6)和Flask开发python项目,在其中我必须返回阿拉伯语文本。当我在控制台中打印文本时,效果很好,但是当我将其作为响应返回时,其顺序从右到左更改。
这是我尝试过的:
from odoa import ODOA
import arabic_reshaper
from bidi.algorithm import get_display
from flask import Flask
import json
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
@app.route('/', methods=['GET'])
def get_an_ayah():
odoa = ODOA()
surah = odoa.get_random_surah(lang='en')
text = surah.ayah.decode("utf-8")
reshaped_text = arabic_reshaper.reshape(text) # correct its shape
arabic_text = get_display(reshaped_text, base_dir='R')
print(arabic_text)
translation = str(surah.translate)
sound_file_url = str(surah.sound)
reference = str(str(surah.surah_number) + ':' + str(surah.ayah_number))
response_dict = {
'text': arabic_text,
'translation': translation,
'sound': sound_file_url,
'ref': reference
}
return response_dict
print(arabix_text
的结果是:
这是它的响应方式:
{
"ref": "94:2",
"sound": "https://raw.githubusercontent.com/semarketir/quranjson/master/source/audio/094/002.mp3",
"text": "ﻙﺭﺯﻭ ﻚﻨﻋ ﺎﻨﻌﺿﻭﻭ",
"translation": "And lift from you your burden."
}
如何获得阿拉伯文字的正确方向?
您真的需要arabic_reshaper和python-bidi吗?
改为尝试以下代码:
from odoa import ODOA
from flask import Flask
import json
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
@app.route('/', methods=['GET'])
def get_an_ayah():
odoa = ODOA()
surah = odoa.get_random_surah(lang='en')
text = surah.ayah.decode("utf-8")
translation = str(surah.translate)
sound_file_url = str(surah.sound)
reference = str(str(surah.surah_number) + ':' + str(surah.ayah_number))
response_dict = {
'text': text,
'translation': translation,
'sound': sound_file_url,
'ref': reference
}
return response_dict
输出文本将带有阿拉伯音调符号。如果要删除变音符号,请使用以下正则表达式替换:
import re
ARABIC_DIACRITICS_PATTERN = re.compile(
'['
'\u0610-\u061a'
'\u064b-\u065f'
'\u0670'
'\u06d6-\u06dc'
'\u06df-\u06e8'
'\u06ea-\u06ed'
'\u08d4-\u08e1'
'\u08d4-\u08ed'
'\u08e3-\u08ff'
']',
)
text_without_diacritics = re.sub(ARABIC_DIACRITICS_PATTERN, '', text)