我正在编写一个Python脚本以从文件读取Unicode字符并将它们插入到数据库中。我只能插入每个字符串的30个字节。 在插入数据库之前,如何计算字符串的大小(以字节为单位)?计算python中的Unicode字符的字节数
0
A
回答
1
假设您正在将文件中的Unicode字符读入名为byteString
的变量中。如果你需要知道的字节数(文件大小),然后就打电话
bytes_count = os.path.getsize(filename)
unicode_string = byteString.decode("utf-8")
print len(unicode_string)
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
这应该是被接受的答案。 –
相关问题
- 1. Python的unicode字符串和字节
- 2. 计算ASCII和Unicode混合字符串中的字符数
- 3. 如何计算unicode字符超过1个字节的字符串长度?
- 4. Python - 计算文件中的字符数
- 5. 计算字符串中的字符数
- 6. __str__中的Python unicode字符
- 7. 计算MB的字节数
- 8. Python:计算字符串中给定字符的出现次数
- 9. 如何计算Python字符串中每个字符的数量?
- 10. Unicode字符串为Unicode字符,Python 3
- 11. 有谁知道如何计算字符串中的字节数?
- 12. unicode字节中的特殊字符比iso字节长吗?
- 13. 拆分字符串,unicode,unicode,python中的字符串
- 14. 计算plsql中字符串的字数
- 15. 计算字符串中的字数?
- 16. 计算数组中的字母字符?
- 17. Javascript计算字符串中的数字
- 18. 如何计算python中的字符串中的字符匹配?
- 19. 计算列表中的字符串中的字符,Python
- 20. python的字符串是unicode字符
- 21. Python-计算数据帧中每个字符串的数字字符总和
- 22. Python中,字符串,Unicode字符
- 23. 计算字节
- 24. Python 3中的Unicode字符与Python 2
- 25. Unicode字符串中的奇数字符
- 26. 字符串python中的字母计数
- 27. Python - pyparsing unicode字符
- 28. Unicode数字的字符类
- 29. Python:解析JSON字符串时处理破解的unicode字节
- 30. 计算字符数组中的一行中的字符数
'uniChars'是误导(你想在'bytes'对象上调用'.decode()';你不应该在Unicode文本中调用它)。您可能会改为'bytestring'。 – jfs