用数字表示阿拉伯字母的Python代码
for i in t.split('\n'):
arabic_string = arabic_reshaper.reshape(i)
arabic_string = arabic_string[::-1]
w = pdf.get_string_width(arabic_string) + 6
pdf.cell(w, 9, arabic_string, 0, 1, 'C', 0)
问题是变量 t 中的数字也被翻转了,比如 48 变成了 84。我需要一个解决办法,请帮忙。
1 个回答
1
你可以通过把字符串拆分成单词,检查每个单词是否是数字,然后只反转那些不是数字的部分,来避免这个问题。
import arabic_reshaper
from bidi.algorithm import get_display
def reverse_arabic_string_with_numbers(t):
reversed_lines = []
for line in t.split('\n'):
words = line.split()
reversed_words = []
for word in words:
if word.isnumeric():
reversed_words.append(word)
else:
arabic_word = arabic_reshaper.reshape(word)
arabic_word = arabic_word[::-1]
arabic_word_display = get_display(arabic_word)
reversed_words.append(arabic_word_display)
reversed_lines.append(' '.join(reversed_words))
return '\n'.join(reversed_lines)
#usage:
t = "مرحبا 48"
reversed_text = reverse_arabic_string_with_numbers(t)