我有一个文本文件,出版商(美国证券交易委员会)声称用UTF-8编码(https://www.sec.gov/files/aqfs.pdf,第4节).我正在使用以下代码处理这些行:
def tags(filename):
"""Yield Tag instances from tag.txt."""
with codecs.open(filename, 'r', encoding='utf-8', errors='strict') as f:
fields = f.readline().strip().split('\t')
for line in f.readlines():
yield process_tag_record(fields, line)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Traceback (most recent call last):
File "/home/randm/Projects/finance/secxbrl.py", line 151, in <module>
main()
File "/home/randm/Projects/finance/secxbrl.py", line 143, in main
all_tags = list(tags("tag.txt"))
File "/home/randm/Projects/finance/secxbrl.py", line 109, in tags
content = f.read()
File "/home/randm/Libraries/anaconda3/lib/python3.6/codecs.py", line 698, in read
return self.reader.read(size)
File "/home/randm/Libraries/anaconda3/lib/python3.6/codecs.py", line 501, in read
newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf-8' codec …Run Code Online (Sandbox Code Playgroud) 好的,所以python3和unicode.我知道所有python3字符串实际上都是unicode字符串,所有python3代码都存储为utf-8.但python3如何读取文本文件?是否假设它们是以utf-8编码的?在阅读文本文件时是否需要调用decode('utf-8')?pandas read_csv()和to_csv()怎么样?
这与我的问题在某种程度上相关.
我处理通过HTTP获取的大量文本(主要是HTML和XML).我正在寻找一个python中的库,它可以根据不同的策略进行智能编码检测,并使用最佳的字符编码猜测将文本转换为unicode.
我发现chardet非常适合自动检测.然而,自动检测一切都是问题,因为它是缓慢的,并且非常违反所有标准.根据chardet 常见问题,我不想搞砸标准.
从同一个常见问题解答这里是我想要寻找编码的地方列表:
Content-type标头中的charset参数.<meta http-equiv="content-type"><head>HTML文档网页中的元素.基本上我希望能够查看所有这些地方并自动处理冲突的信息.
那里有这样的图书馆还是我需要自己写呢?
我比Python或文本编码更了解自行车修理,电锯使用和沟槽安全; 考虑到这一点...
Python的文本编码似乎是一个长期的问题(我自己的问题:?搜索文本文件与Python的各种编码的内容,和其他人我读过:1,2我已经采取了尝试写一些代码来猜测.编码如下.
在有限的测试中,这段代码似乎可以用于我的目的*,而不必知道文本编码的前三个字节以及这些数据不提供信息的情况.
*我的目的是:
问:什么是用一个什么,我认为是比较和像我这样做如下计算字符的klutzy方法的缺陷?任何输入都非常感谢.
def guess_encoding_debug(file_path):
"""
DEBUG - returns many 2 value tuples
Will return list of all possible text encodings with a count of the number of chars
read that are common characters, which might be a symptom of success.
SEE warnings in sister function
"""
import codecs
import string
from operator import itemgetter
READ_LEN = 1000
ENCODINGS = ['ascii','cp1252','mac_roman','utf_8','utf_16','utf_16_le',\
'utf_16_be','utf_32','utf_32_le','utf_32_be']
#chars in the regular ascii …Run Code Online (Sandbox Code Playgroud) 之前我已经在Stack Overflow上以循环方式询问了这个问题,并希望这次能够做到正确.如何将ANSI(代码页1252)转换为UTF-8,同时保留特殊字符?(我知道UTF-8支持比ANSI更大的字符集,但是如果我可以保留ANSI支持的所有UTF-8字符并用其他?东西替换其余的字符集就可以了)
为什么我要转换ANSI→UTF-8
我基本上编写的程序将vCard文件(VCF)拆分为单个文件,每个文件包含一个联系人.我注意到诺基亚和索尼爱立信手机以UTF-8(无BOM)保存备份VCF文件,但Android将其保存为ANSI(1252).上帝知道其他手机以什么格式保存它们!
所以我的问题是
tl; dr 需要知道如何将字符编码从(ANSI/UTF8)转换为(UTF8/ANSI),同时保留所有特殊字符.
我知道这bytes.decode给出了一个字符串并string.encode给出了字节,但前提encoding是使用了正确的。
假设我有一个使用编码的字节对象gb18030
如果我尝试使用big5以下方法对其进行解码:
>>name = '?? damon'
>>b1 = name.encode('gb18030')
>>> b1.decode('big5')
UnicodeDecodeError: 'big5' codec can't decode byte 0xc8 in position 2: illegal multibyte sequence
Run Code Online (Sandbox Code Playgroud)
有什么方法可以从bytes对象中找到编码吗?
我在python3文档中找不到这方面的任何有用的 api 。
有没有办法预处理文本文件并跳过这些字符?
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa1 in position 1395: invalid start byte
Run Code Online (Sandbox Code Playgroud) 我在使用需要打开不同编码的文件的Python脚本时遇到了一些问题.
我通常使用这个:
with open(path_to_file, 'r') as f:
first_line = f.readline()
Run Code Online (Sandbox Code Playgroud)
当文件正确编码时,这很有用.
但有时,它不起作用,例如使用此文件,我有这个:
In [22]: with codecs.open(filename, 'r') as f:
...: a = f.readline()
...: print(a)
...: print(repr(a))
...:
??Test for StackOverlow
'\xff\xfeT\x00e\x00s\x00t\x00 \x00f\x00o\x00r\x00 \x00S\x00t\x00a\x00c\x00k\x00O\x00v\x00e\x00r\x00l\x00o\x00w\x00\r\x00\n'
Run Code Online (Sandbox Code Playgroud)
我想在这些方面搜索一些东西.可悲的是,用这种方法,我不能:
In [24]: "Test" in a
Out[24]: False
Run Code Online (Sandbox Code Playgroud)
我在这里发现了很多问题,指的是同一类型的问题:
但无法设法正确解码文件...
使用codecs.open():
In [17]: with codecs.open(filename, 'r', "utf-8") as f:
a = f.readline()
print(a)
....:
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-17-0e72208eaac2> in <module>()
1 with codecs.open(filename, 'r', "utf-8") …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用此函数将多个 CSV 文件合并为一个:
import glob
path = r'/content/drive/My Drive/DatiAirQuality/MI_Air_Quality/data'
all_files = glob.glob(path + "/*.csv")
li = []
for filename in all_files:
df = pd.read_csv(filename, index_col=None, header=0)
li.append(df)
frame = pd.concat(li, axis=0, ignore_index=True)
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:“utf-8”编解码器无法解码位置 0 中的字节 0xb5:无效的起始字节
这是回溯:
8 for filename in all_files:
----> 9 df = pd.read_csv(filename, index_col=None,
header=0)
10 li.append(df)
11
Run Code Online (Sandbox Code Playgroud)
感谢你。
python ×7
encoding ×3
unicode ×3
utf-8 ×3
python-3.x ×2
.net ×1
c# ×1
csv ×1
decode ×1
html ×1
http ×1
python-2.7 ×1
string ×1
text-files ×1
xml ×1