将unicode输入转换为字符串以进行比较

0 投票
4 回答
2706 浏览
提问于 2025-04-16 20:10

我正在写一段代码,这段代码的作用是解析一个Word文档中的表格,并且把它和一个关键词进行比较,这个关键词是一个ASCII字符串。

tyring = unicode((ListTables[0].Rows[x])).encode('utf-8')
tryingstring = tyring.encode('ascii')
print 'trying string' ,tryingstring

下面是错误信息:

tyring = unicode((ListTables[0].Rows[x])).encode('utf-8','ignore')
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 201, in __str__
    return str(self.__call__())
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 201, in __str__
    return str(self.__call__())
UnicodeEncodeError: 'ascii' codec can't encode character u'\uf07a' in position 0: ordinal not in range(128)

它没有打印出来,但应该打印的,因为现在尝试的字符串是一个ASCII字符串,对吧?

4 个回答

0

你是用 codecs.open() 来打开文件的吗?在这个函数里你可以指定文件的编码方式。

http://docs.python.org/library/codecs.html

0

试试这个,我在想这是否会有帮助:

if tr1_find.search(unicode(ListTables[0].Cell(x,y)).encode('utf-8','ignore')):

你可能还会觉得这个Python文档的页面很有用:http://docs.python.org/howto/unicode.html

它正好讲了这种问题。

2

回到你最初的提问:

if tr1_find.search(str(ListTables[0].Cell(x,y))):
    print 'Found'
    value  = ListTables[0].Cell(x,y+1)

ListTables[0].Cell(x,y) 会从Word文档中返回一个 Cell 实例。调用 str() 方法会获取它的Unicode值,并尝试用 ascii 编码将其转换为字节字符串。由于它包含非ASCII字符,所以会出现 UnicodeEncodingError 错误。

在你后来的修改中:

tyring = unicode((ListTables[0].Rows[x])).encode('utf-8')
tryingstring = tyring.encode('ascii')
print 'trying string' ,tryingstring

unicode 可以获取Unicode值,将其转换为UTF-8字节字符串,并存储在 tyring 中。接下来的那一行又尝试将字节字符串编码为 'ascii'。这不合法,因为只有Unicode字符串才能被编码,所以Python首先尝试使用默认的 'ascii' 编码将字节字符串转换回Unicode字符串。这会导致 UnicodeDecodingError 错误(而不是编码错误)。

最佳实践是所有字符串处理都使用Unicode。你缺少的是 Range() 方法来获取单元格的值。以下是一个访问Word文档表格的示例:

PythonWin 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32.
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information.
>>> import win32com.client
>>> word=win32com.client.gencache.EnsureDispatch('Word.Application')
>>> word.ActiveDocument.Tables[0].Cell(1,1).Range()
u'One\u4e00\r\x07'

注意它是一个Unicode字符串。Word似乎也使用 \r\x07 作为单元格行的结束符。

现在你可以测试这个值:

>>> value = word.ActiveDocument.Tables[0].Cell(1,1).Range()
>>> value == 'One'   # NOTE: Python converts byte strings to Unicode via the default codec ('ascii' in Python 2.X)
False
>>> value == u'One'
False
>>> value == u'One马\r\x07'
False
>>> value == u'One一\r\x07'
True
>>> value == u'One\u4e00\r\x07'
True
>>> value == 'One\x92' # non-ASCII byte string fails to convert
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

撰写回答