Python正则表达式与版权符号

8 投票
2 回答
9903 浏览
提问于 2025-04-17 17:23

编辑

有个有趣的故事,我在搜索之前先清理文本,而我清理的过程之一就是去掉所有那些符号。所以我用的正则表达式其实是没问题的 :) 不过还是谢谢大家的帮助!

原文

我想用Python和正则表达式在一个UTF8文本文件中找到版权符号©。我遇到的问题是我不知道怎么在正则表达式中表示这个版权符号。

我还想找TM和(R)这两个符号,如果能帮我找到就太好了,不过我觉得只要找到了(C),其他的应该也能简单搞定。

我一直在谷歌上努力寻找答案,但还没找到任何有效的方法。

如果有聪明的人能告诉我,那就太感谢了!

谢谢!

2 个回答

4

你是在找像这样的东西吗?

import re

text = 'StackOverflow® © 2013 - A great place to code™'
for m in re.finditer(r"[©®™]", text):
    print '%02d-%02d: %s' % (m.start(), m.end(), m.group(0))

这个的输出结果是:

13-14: ®
15-16: ©
45-46: ™
11

你可以把你的文本转换成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>

有一些网页 列出了 所有的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'

撰写回答