【发布时间】:2014-11-16 16:42:20
【问题描述】:
在 java 中,我可以使用正则表达式:\p{Sc} 来检测文本中的货币符号。 Python中的等价物是什么?
【问题讨论】:
在 java 中,我可以使用正则表达式:\p{Sc} 来检测文本中的货币符号。 Python中的等价物是什么?
【问题讨论】:
使用regex包可以使用unicode类:
>>> import regex
>>> regex.findall(r'\p{Sc}', '$99.99 / €77') # Python 3.x
['$', '€']
>>> regex.findall(ur'\p{Sc}', u'$99.99 / €77') # Python 2.x (NoteL unicode literal)
[u'$', u'\xa2']
>>> print _[1]
¢
更新
使用unicodedata.category的另一种方式:
>>> import unicodedata
>>> [ch for ch in '$99.99 / €77' if unicodedata.category(ch) == 'Sc']
['$', '€']
【讨论】:
regex 太棒了。 That's just the tip of the iceberg.
如果您想坚持使用re,请提供characters from Sc manually:
u"[$¢£¤¥֏؋৲৳৻૱௹฿៛\u20a0-\u20bd\ua838\ufdfc\ufe69\uff04\uffe0\uffe1\uffe5\uffe6]"
会的。
【讨论】:
\u20a0-\u20bd 中:€ 是\u20ac。
currency_symbols = u''.join(unichr(i) for i in range(0xffff) if unicodedata.category(unichr(i)) == 'Sc')