简体   繁体   English

解码文本文件中的字符串

[英]Decoding strings from textfile

I have a text file that is reading in another application's script. 我有一个文本文件正在另一个应用程序的脚本中读取。 This how it looks like in notepad: 在记事本中的外观如下:

Одинцовская РЭС: М.О., Одинцовский район
Климовская РЭС: М.О., г.о. Подольск
Кульшовская РЭС: М.О., г.о. Подольск

This file is needed for two things: 1. Creating a dict of values, separated by ':'. 该文件用于两件事:1.创建值的字典,以':'分隔。 I use this dict in another part of script 2. Allows user to select desirable value 我在脚本2的另一部分中使用了该字典。允许用户选择所需的值。

在此处输入图片说明

Here is what user see when he launhes script. 这是用户启动脚本时看到的内容。 When a certain value is selected I have to use it in dictionary. 选择某个值后,我必须在字典中使用它。 But the problem is that selection is in unicode format (because of features of script building in ArcGIS) while the dictionary's keys are str . 但是问题在于,字典的键是str ,选择是采用unicode格式的(因为ArcGIS中脚本构建的功能)。 So I need a value in dictionary which looks like '\\xce\\xe4\\xe8\\xed\\xf6\\xee\\xe2\\xf1\\xea\\xe0\\xff \\xd0\\xdd\\xd1' to be converted in unicode. 所以我需要在字典中看起来像'\\xce\\xe4\\xe8\\xed\\xf6\\xee\\xe2\\xf1\\xea\\xe0\\xff \\xd0\\xdd\\xd1'才能在Unicode中转换。 But when I make .encode('utf-8') it throws an error 但是当我制作.encode('utf-8')会引发错误

UnicodeDecodeError: 'ascii' codec can't decode byte 0xce in position 0: ordinal not in range(128)

This should work 这应该工作

>>> c = b'\xce\xe4\xe8\xed\xf6\xee\xe2\xf1\xea\xe0\xff \xd0\xdd\xd1'
>>> c
b'\xce\xe4\xe8\xed\xf6\xee\xe2\xf1\xea\xe0\xff \xd0\xdd\xd1'
>>> c.decode('unicode_escape')
'Îäèíöîâñêàÿ ÐÝÑ'

The b'' prefix denotes sequence of 8-bit bytes. b''前缀表示8位字节的序列。

Take a look at SO read russian characters 看看所以读俄语字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM