Python 正则表达式和版权符号

标签 python regex text utf-8

编辑

有趣的是,我在搜索文本之前清理了文本,清理过程的一部分是删除所有这些符号。因此,我使用的正则表达式工作得很好 :) 无论如何,谢谢大家的帮助!

原创

我正在尝试使用 python 和正则表达式检测 UTF8 文本文档中的版权符号 ©。我遇到的问题是我不知道如何在正则表达式中表示版权符号。

我还将寻找 TM 和 (R),因此也将非常感激,尽管我怀疑一旦我拥有 (C),确定其他人会很简单。

我一直在 google 上勇敢地寻找答案,但还没有找到任何有用的东西。

如果一些明亮的 Spark 可以告诉我,将不胜感激!

谢谢!

最佳答案

您可以将文本转换为 unicode 并使用 unicode 正则表达式模式。

这些是您提到的三个符号:

In [213]: print(u'\N{COPYRIGHT SIGN} \N{TRADE MARK SIGN} \N{REGISTERED SIGN}')
© ™ ®

这里是一些utf-8编码的字符串:

In [223]: content = u'\N{TRADE MARK SIGN}'.encode('utf-8')

这里我们将其转换为unicode:

In [224]: text = content.decode('utf-8')

这是对以下三个符号中任何一个的正则表达式搜索:

In [225]: re.search(u'(\N{COPYRIGHT SIGN}|\N{TRADE MARK SIGN}|\N{REGISTERED SIGN})', text)
Out[225]: <_sre.SRE_Match at 0x9a1ebe0>

webpages which catalog每个 unicode 字符。但是指定的unicode码位有几十万个,手动浏览查找字符是行不通的。

所以,我编写了下面的程序来按名称搜索 unicode。

import sys
import unicodedata as ud
import re
import argparse
import functools

__usage__ = '''\
unicode_lookup.py -u '\d'    # Shows all unicode symbols that regex match '\d'
unicode_lookup.py number     # Shows all unicode symbols whose name regex matches 'number'
'''


def lookup(name_pat=None, from_num=0, to_num=0x10ffff, unicode_pattern=None,
           category_pattern=None, ignore_unnamed=True,
           combining=False):
    fmt = u"{symbol} {num} {cat} {bi} {w} {comb} {mir} '{name}'"
    print(fmt.format(
        symbol='Symbol', num='Num', name='NAME',
        cat='Category', bi='Bidirectional', w='Width',
        comb='Combining', mir='Mirrored'))
    for num in range(from_num, to_num + 1):
        s = unichr(num)
        if unicode_pattern and not unicode_pattern.match(s):
            continue
        category = ud.category(s)
        if category_pattern and not category_pattern.match(category):
            continue
        try:
            name = ud.name(s)
            if name_pat and not name_pat.search(name):
                continue
        except ValueError:
            if ignore_unnamed:
                continue
            else:
                name = '?'
        bidirectional = ud.bidirectional(s)
        combining_class = ud.combining(s)
        if combining and not combining_class:
            continue
        mirrored = ud.mirrored(s)
        width = ud.east_asian_width(s)
        data = dict(num=num, symbol=s, name=name,
                    cat=category, bi=bidirectional, w=width,
                    comb=combining_class, mir=mirrored)
        print(fmt.format(**data).encode('utf-8'))


def parse_options():
    parser = argparse.ArgumentParser(
        epilog=__usage__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('name_pat',
                        type=functools.partial(re.compile, flags=re.IGNORECASE))
    parser.add_argument('-f', '--from_num', default=0, type=int)
    parser.add_argument('-t', '--to_num', default=0x10ffff, type=int)
    parser.add_argument('-u', '--unicode_pattern',
                        type=functools.partial(re.compile, flags=re.UNICODE))
    parser.add_argument('--category_pattern', type=re.compile)
    parser.add_argument('--show_unnamed', action='store_true')
    parser.add_argument('--combining', action='store_true')
    return parser.parse_args()

if __name__ == '__main__':
    opt = parse_options()
    lookup(name_pat=opt.name_pat, from_num=opt.from_num, to_num=opt.to_num,
           unicode_pattern=opt.unicode_pattern,
           category_pattern=opt.category_pattern,
           ignore_unnamed=not opt.show_unnamed,
           combining=opt.combining)

运行

% unicode_lookup.py "copyright|trade|registered"

产量

Symbol Num Category Bidirectional Width Combining Mirrored 'NAME'
© 169 So ON N 0 0 'COPYRIGHT SIGN'
® 174 So ON A 0 0 'REGISTERED SIGN'
℗ 8471 So ON N 0 0 'SOUND RECORDING COPYRIGHT'
™ 8482 So ON A 0 0 'TRADE MARK SIGN'

关于Python 正则表达式和版权符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15125465/

相关文章:

python - 将成员函数动态添加到Python中的类实例

javascript - 查询 JavaScript 代码的范围

matlab - 在MATLAB中显示文本文档

html - 如何获取html页面的 "Text"? (网络浏览器 - 德尔福)

html - 是否有 css 文本重置?

python - 在 sqlalchemy 的 ORM(postgresql 数据库)中自动截断字符串

python - 当你添加一个带有 numpy 数组的张量时会发生什么?

regex - 除了空格用双引号引起来之外,Perl如何在空格上分割行?

python - 为 6 个字符的代码编写正则表达式

javascript - 奇怪的空格字符无法匹配