2015-06-03 54 views
0

我正在编写一个Python脚本以从文件读取Unicode字符并将它们插入到数据库中。我只能插入每个字符串的30个字节。 在插入数据库之前,如何计算字符串的大小(以字节为单位)?计算python中的Unicode字符的字节数

回答

1

假设您正在将文件中的Unicode字符读入名为byteString的变量中。如果你需要知道的字节数(文件大小),然后就打电话
bytes_count = os.path.getsize(filename)

unicode_string = byteString.decode("utf-8") 
print len(unicode_string) 
+0

'uniChars'是误导(你想在'bytes'对象上调用'.decode()';你不应该在Unicode文本中调用它)。您可能会改为'bytestring'。 – jfs

4

:然后你就可以执行以下操作。


如果你想找出一个Unicode字符可以有多少字节需要那就要看字符编码:

>>> print(u"\N{EURO SIGN}") 
€ 
>>> u"\N{EURO SIGN}".encode('utf-8') # 3 bytes 
'\xe2\x82\xac' 
>>> u"\N{EURO SIGN}".encode('cp1252') # 1 byte 
'\x80' 
>>> u"\N{EURO SIGN}".encode('utf-16le') # 2 bytes 
'\xac ' 

要找出多少Unicode字符的文件包含,你不需要一次读取内存中的整个文件(如果它是一个大文件):

with open(filename, encoding=character_encoding) as file: 
    unicode_character_count = sum(len(line) for line in file) 

如果你ar e在Python 2上,然后在顶部添加from io import open

对于相同的人类可读的文本可以取决于Unicode的正常化(不同的环境可能会使用不同的设置)的确切计数:

>>> import unicodedata 
>>> print(u"\u212b") 
Å 
>>> unicodedata.normalize("NFD", u"\u212b") # 2 Unicode codepoints 
u'A\u030a' 
>>> unicodedata.normalize("NFC", u"\u212b") # 1 Unicode codepoint 
u'\xc5' 
>>> unicodedata.normalize("NFKD", u"\u212b") # 2 Unicode codepoints 
u'A\u030a' 
>>> unicodedata.normalize("NFKC", u"\u212b") # 1 Unicode codepoint 
u'\xc5' 

如示例所示,一个字符(A)可以用几个Unicode代码点表示。

要找出多少用户感知的字符在文件中,你可以使用\X正则表达式(伯爵伸出素群):

import regex # $ pip install regex 

with open(filename, encoding=character_encoding) as file: 
    character_count = sum(len(regex.findall(r'\X', line)) for line in file) 

例子:

>>> import regex 
>>> char = u'A\u030a' 
>>> print(char) 
Å 
>>> len(char) 
2 
>>> regex.findall(r'\X', char) 
['Å'] 
>>> len(regex.findall(r'\X', char)) 
1 
+1

这应该是被接受的答案。 –