Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python和Postgres中处理批处理数据库导入中的重音字符_Python_Django_Postgresql - Fatal编程技术网

如何在Python和Postgres中处理批处理数据库导入中的重音字符

如何在Python和Postgres中处理批处理数据库导入中的重音字符,python,django,postgresql,Python,Django,Postgresql,在Python(openblock)中运行批导入脚本时,我得到以下用于编码“UTF8”的无效字节序列:重音字符的0xca4e错误: 它显示为: 大教堂 但实际上是“大千世界” 处理这个问题的最佳方法是什么?理想情况下,我希望保留重音字符。我想我需要对它进行编码 编辑:是什么?实际上应该是Ê。还请注意,该变量来自ESRI形状文件。当我尝试davidcrow的解决方案时,我得到了“Unicode不受支持”,因为假定没有重音字符的字符串已经是Unicode字符串 以下是我使用的ESRIImporter

在Python(openblock)中运行批导入脚本时,我得到以下用于编码“UTF8”的无效字节序列:重音字符的0xca4e错误:

它显示为: 大教堂

但实际上是“大千世界”

处理这个问题的最佳方法是什么?理想情况下,我希望保留重音字符。我想我需要对它进行编码

编辑:是什么?实际上应该是Ê。还请注意,该变量来自ESRI形状文件。当我尝试davidcrow的解决方案时,我得到了“Unicode不受支持”,因为假定没有重音字符的字符串已经是Unicode字符串

以下是我使用的ESRIImporter代码:

from django.contrib.gis.gdal import DataSource

class EsriImporter(object):
    def __init__(self, shapefile, city=None, layer_id=0):
        print >> sys.stderr, 'Opening %s' % shapefile
        ds = DataSource(shapefile)

        self.layer = ds[layer_id]
        self.city = "OTTAWA" #city and city or Metro.objects.get_current().name
        self.fcc_pat = re.compile('^(' + '|'.join(VALID_FCC_PREFIXES) + ')\d$')

    def save(self, verbose=False):
        alt_names_suff = ('',)
        num_created = 0
        for i, feature in enumerate(self.layer):
            #if not self.fcc_pat.search(feature.get('FCC')):
            #    continue
            parent_id = None
            fields = {}
            for esri_fieldname, block_fieldname in FIELD_MAP.items():
                value = feature.get(esri_fieldname)
                #print >> sys.stderr, 'Looking at %s' % esri_fieldname

                if isinstance(value, basestring):
                    value = value.upper()
                elif isinstance(value, int) and value == 0:
                    value = None
                fields[block_fieldname] = value
            if not ((fields['left_from_num'] and fields['left_to_num']) or
                    (fields['right_from_num'] and fields['right_to_num'])):
                continue
            # Sometimes the "from" number is greater than the "to"
            # number in the source data, so we swap them into proper
            # ordering
            for side in ('left', 'right'):
                from_key, to_key = '%s_from_num' % side, '%s_to_num' % side
                if fields[from_key] > fields[to_key]:
                    fields[from_key], fields[to_key] = fields[to_key], fields[from_key]
            if feature.geom.geom_name != 'LINESTRING':
                continue
            for suffix in alt_names_suff:
                name_fields = {}
                for esri_fieldname, block_fieldname in NAME_FIELD_MAP.items():
                    key = esri_fieldname + suffix
                    name_fields[block_fieldname] = feature.get(key).upper()
                    #if block_fieldname == 'postdir':
                        #print >> sys.stderr, 'Postdir block %s' % name_fields[block_fieldname]


                if not name_fields['street']:
                    continue
                # Skip blocks with bare number street names and no suffix / type
                if not name_fields['suffix'] and re.search('^\d+$', name_fields['street']):
                    continue
                fields.update(name_fields)
                block = Block(**fields)
                block.geom = feature.geom.geos
                print repr(fields['street'])
                print >> sys.stderr, 'Looking at block %s' % unicode(fields['street'], errors='replace' )

                street_name, block_name = make_pretty_name(
                    fields['left_from_num'],
                    fields['left_to_num'],
                    fields['right_from_num'],
                    fields['right_to_num'],
                    '',
                    fields['street'],
                    fields['suffix'],
                    fields['postdir']
                )
                block.pretty_name = unicode(block_name)
                #print >> sys.stderr, 'Looking at block pretty name %s' % fields['street']

                block.street_pretty_name = street_name
                block.street_slug = slugify(' '.join((unicode(fields['street'], errors='replace' ), fields['suffix'])))
                block.save()
                if parent_id is None:
                    parent_id = block.id
                else:
                    block.parent_id = parent_id
                    block.save()
                num_created += 1
                if verbose:
                    print >> sys.stderr, 'Created block %s' % block
        return num_created
输出:

'GRAND-CH\xcaNE, COUR DU'
Looking at block GRAND-CH�NE, COUR DU
Traceback (most recent call last):

  File "../blocks_ottawa.py", line 144, in <module>
    sys.exit(main())
  File "../blocks_ottawa.py", line 139, in main
    num_created = esri.save(options.verbose)
  File "../blocks_ottawa.py", line 114, in save
    block.save()
  File "/home/chris/openblock/src/django/django/db/models/base.py", line 434, in save
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)
  File "/home/chris/openblock/src/django/django/db/models/base.py", line 527, in save_base
    result = manager._insert(values, return_id=update_pk, using=using)
  File "/home/chris/openblock/src/django/django/db/models/manager.py", line 195, in _insert
    return insert_query(self.model, values, **kwargs)
  File "/home/chris/openblock/src/django/django/db/models/query.py", line 1479, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/chris/openblock/src/django/django/db/models/sql/compiler.py", line 783, in execute_sql
    cursor = super(SQLInsertCompiler, self).execute_sql(None)
  File "/home/chris/openblock/src/django/django/db/models/sql/compiler.py", line 727, in execute_sql
    cursor.execute(sql, params)
  File "/home/chris/openblock/src/django/django/db/backends/util.py", line 15, in execute
    return self.cursor.execute(sql, params)
  File "/home/chris/openblock/src/django/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute
    return self.cursor.execute(query, args)

django.db.utils.DatabaseError: invalid byte sequence for encoding "UTF8": 0xca4e
HINT:  This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding".
'GRAND-CH\xcaNE,COUR DU'
看看block GRAND-CH�不,你在哪里
回溯(最近一次呼叫最后一次):
文件“./blocks_ottawa.py”,第144行,在
sys.exit(main())
文件“./blocks_ottawa.py”,第139行,主
num_created=esri.save(options.verbose)
文件“./blocks_ottawa.py”,第114行,保存
block.save()
文件“/home/chris/openblock/src/django/django/db/models/base.py”,第434行,保存
self.save_base(使用=使用,强制插入=强制插入,强制更新=强制更新)
文件“/home/chris/openblock/src/django/django/db/models/base.py”,第527行,在save_base中
结果=管理器。\u插入(值,返回\u id=update\u pk,using=using)
文件“/home/chris/openblock/src/django/django/db/models/manager.py”,第195行,插入
返回insert_查询(self.model,value,**kwargs)
文件“/home/chris/openblock/src/django/django/db/models/query.py”,第1479行,插入查询
return query.get\u编译器(using=using).execute\u sql(return\u id)
文件“/home/chris/openblock/src/django/django/db/models/sql/compiler.py”,第783行,在execute\u sql中
cursor=super(SQLInsertCompiler,self)。执行\u sql(无)
execute_sql中的文件“/home/chris/openblock/src/django/django/db/models/sql/compiler.py”,第727行
cursor.execute(sql,params)
文件“/home/chris/openblock/src/django/django/db/backends/util.py”,执行中的第15行
返回self.cursor.execute(sql,params)
文件“/home/chris/openblock/src/django/django/db/backends/postgresql_psycopg2/base.py”,第44行,在execute中
返回self.cursor.execute(查询,参数)
django.db.utils.DatabaseError:编码“UTF8”的字节序列无效:0xca4e
提示:如果字节序列与服务器期望的编码不匹配(由“client_encoding”控制),也可能发生此错误。

您可以尝试以下方法:

usting=unicode(item.field,“utf-8”)


有关Unicode和Python的更多详细信息,请参阅。

看起来数据不是以UTF-8格式发送的。。。因此,检查DB会话中的client_encoding参数是否与数据匹配,或者在读取文件时将其转换为Python中的UTF-8/Unicode


您可以使用“SET client_encoding='ISO-8859-1'”或类似方法更改DB会话的客户端编码。不过,0xca在拉丁语1中不是E-with-grave,因此我不确定您的文件使用的是哪个字符编码?

请提供更多信息。什么平台-Windows/Linux/

什么版本的Python

如果您正在运行Windows,您的编码很可能是
cp1252
或类似编码,而不是
ISO-8859-1
。它绝对不是
UTF-8

你需要:(1)找出你的输入数据是用什么编码的。试试cp1252;这是通常的嫌疑犯。(2) 将数据解码为unicode(3)并将其编码为UTF-8


如何从ESRI形状文件中获取数据?显示您的代码。显示完整的回溯和错误消息。为了避免视觉问题(这是电子坟墓!不,这是电子急性!)
打印报告(可疑数据)
并将结果复制/粘贴到问题编辑中。不要用粗体字。

你只是假设他在python源代码中硬编码他正在数据库中转储的每个字符串?这是唯一一个使用此方法的caise。假设您可以将值分配到对象或列表中。在不知道数据来自何处的情况下,将其抽象为单个字符串是不值得的。在这种情况下,我认为我可以只为单个字符串进行抽象。很抱歉,我没有从一开始就包含代码。@Chris:不,只为单个字符串执行操作是不好的。这样做完全是胡说八道。@John,实际上我的意思是按照您在上面的评论中所指出的方式对其进行编码。。。不是为每个字符串手动执行。循环通过的每个没有任何重音字符的其他字符串都会抛出“不支持解码Unicode”错误,从我可以看出,如果该字符串已经是Unicode,则会发生此错误。因此,似乎问题出在包含重音的字符或字符串上?这个错误到底是从哪里抛出的?我对Python不是很熟悉,但我记得它听起来不像PostgreSQL错误。0xca是ISO-8859-1 btw中的E-with-扬抑,所以这是有意义的。说真的,只需更改db会话的客户端编码设置就可以了,基本上就是将字节解码为字符的责任转移到数据库中。不,您会得到“Unicode不受支持”,因为他的“解决方案”是生成Unicode,而您正在将其提供给不喜欢的东西。不要那样做。@Chris:渥太华->
cp1252
。您应该查看
django.contrib.gis.gdal.DataSource
的文档,看看它是否在任何地方提到了编码。在任何情况下,如果您想要/需要UTF-8格式的数据将其放入数据库,您需要执行
esri_text.decode('whatever')。encode('utf8')
某种方式(可能是两个步骤)。我在文档中没有做任何关于编码的操作,但是解码然后编码工作非常好!非常感谢!在编码的世界里,我还有很多事情要做。