راکت
حل شده

پشتیبانی از زبان فارسی در پایتون

3 پاسخ

سلام کسی میتونه کمک کنه در ماژول dbf پایتون مشکل ساپورت نکردن زبان فارسی رو چجوری حل کنم؟
الان این اررور رو میده
ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

ثبت پرسش جدید

پاسخ‌ها

3
سروش مرشدی
سروش مرشدی
@sorooshMorshedi

تخصص: Senior Software Architect & Full-Stack Engineer

بهترین پاسخ

ممنونم مشکلم حل شد باید encoder ماژول dbf رو تغییر میدادم :
dbf.table(table_name, table_fields, codepage='utf-8')

مهدی مشایخی
مهدی مشایخی
@MahdiMashayekhi

تخصص: برنامه نویس پایتون - ماشین لرنینگ - جنگو

سلام
شما باید ابتدا ستون‌های فارسی رو به صورت یونی‌کد در بیارید و بعد اونها رو به کدینگ مورد نظر تبدیل کنید. برای این کار می‌تونید از کتابخانه ftfy استفاده کنید

مثال

import dbf
import ftfy

def fix_encoding(row):
    for col in row.keys():
        value = row[col]

        if isinstance(value, str) and any(ord(c) > 128 for c in value):
 ftfy
            value = ftfy.fix_text(value)
            row[col] = value

table = dbf.Table('file.dbf')

for row in table:
    fix_encoding(row)

table.flush()

سوالی داشتید در خدمتم

سروش مرشدی
سروش مرشدی
@sorooshMorshedi

تخصص: Senior Software Architect & Full-Stack Engineer

If you're getting:

'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

the problem is not really “Python doesn't support Persian.” Python supports Unicode just fine. Your DBF library is trying to encode Persian text as ASCII, and ASCII obviously has no idea what Persian is. 😄

If you're using dbfread, specify the encoding explicitly:

from dbfread import DBF

table = DBF("file.dbf", encoding="cp1256")

For DBF files created with UTF-8:

table = DBF("file.dbf", encoding="utf-8")

For older Persian/Arabic DBF files, cp1256 (Windows-1256) is usually the first encoding worth trying.

The important part is this: don't randomly change Python's default encoding. The encoding has to match the encoding used when the DBF file was created.

If you're using the dbf package rather than dbfread, the solution is different because you're dealing with DBF creation/writing rather than just reading it.

Soroosh Morshedi
sorooshmorshedi.com

شاید پاسخ شما همین‌جا باشد

برای ارسال پاسخ لازم است وارد شده یا ثبت‌نام کنید

ورود یا ثبت‌نام