在 Python 中将字母和非字母字符与非英语文本分开
separating letters and non alphabetic characters from a non-English text in Python
我正在 Python 2.7 抓取一个葡萄牙语网站,我想将括号内的拉丁单词和数字分开。每个文本看起来像:
text = 'Obras de revisão e recuperação (45453000-7)'
我尝试了以下代码:
#-*- coding: utf-8 -*-
import re
text = u'Obras de revisão e recuperação (45453000-7)'
re.sub(r'\([0-9-]+\)', u'', text).encode("utf8")
输出是:
'Obras de revis\xc3\xa3o e recupera\xc3\xa7\xc3\xa3o '
我也想删除括号并得到如下输出:
name = 'Obras de revisão e recuperação'
code = '45453000-7'
它应该是这样工作的:
文件:/tmp/foo.py
#-*- coding: utf-8 -*-
import re
text = u'Obras de revisão e recuperação (45453000-7)'
print re.sub(r'\([0-9-]+\)', u'', text)
注意,没有.encode('utf-8')
东西。
现在,在 python 控制台中:
>>> import re
>>> text = u'Obras de revisão e recuperação (45453000-7)'
>>> re.sub(r'\([0-9-]+\)', u'', text)
u'Obras de revis\xe3o e recupera\xe7\xe3o '
>>> print re.sub(r'\([0-9-]+\)', u'', text)
Obras de revisão e recuperação
如您所见,print re.sub(..)
(又名 unicode.__str__()
)与 unicode.__repr__()
不同 return。
我怀疑这就是你正在努力解决的问题。
供参考:Difference between __str__ and __repr__ in Python
我正在 Python 2.7 抓取一个葡萄牙语网站,我想将括号内的拉丁单词和数字分开。每个文本看起来像:
text = 'Obras de revisão e recuperação (45453000-7)'
我尝试了以下代码:
#-*- coding: utf-8 -*-
import re
text = u'Obras de revisão e recuperação (45453000-7)'
re.sub(r'\([0-9-]+\)', u'', text).encode("utf8")
输出是:
'Obras de revis\xc3\xa3o e recupera\xc3\xa7\xc3\xa3o '
我也想删除括号并得到如下输出:
name = 'Obras de revisão e recuperação'
code = '45453000-7'
它应该是这样工作的:
文件:/tmp/foo.py
#-*- coding: utf-8 -*-
import re
text = u'Obras de revisão e recuperação (45453000-7)'
print re.sub(r'\([0-9-]+\)', u'', text)
注意,没有.encode('utf-8')
东西。
现在,在 python 控制台中:
>>> import re
>>> text = u'Obras de revisão e recuperação (45453000-7)'
>>> re.sub(r'\([0-9-]+\)', u'', text)
u'Obras de revis\xe3o e recupera\xe7\xe3o '
>>> print re.sub(r'\([0-9-]+\)', u'', text)
Obras de revisão e recuperação
如您所见,print re.sub(..)
(又名 unicode.__str__()
)与 unicode.__repr__()
不同 return。
我怀疑这就是你正在努力解决的问题。
供参考:Difference between __str__ and __repr__ in Python