V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
paloalto
V2EX  ›  编程

如何用正则一次性替换所有的@username为@nickanme?有比.replace()更好的办法吗?已附代码示例。

  •  
  •   paloalto · Feb 1, 2013 · 3538 views
    This topic created in 4846 days ago, the information mentioned may be changed or developed.


    重复replace() 伤不起啊。。
    7 replies    1970-01-01 08:00:00 +08:00
    keakon
        1
    keakon  
       Feb 1, 2013
    没看懂你干啥,你是要re.sub()么?
    paloalto
        2
    paloalto  
    OP
       Feb 1, 2013
    @keakon 啊简单的说就是想把字符串 '@post-rocker @post-rocker' 替换为:

    '@<a href="/member/post-rocker">孬爷爷&nbsp;biu一&nbsp;声</a> @<a href="/member/post-rocker">孬爷爷&nbsp;biu一&nbsp;声</a>'
    paloalto
        3
    paloalto  
    OP
       Feb 1, 2013
    哈哈哈

    >>> comment = '@post-rocker @post-rocker :请查看@ailuoli 的文章'
    >>> stra = re.compile(r'@([a-zA-Z0-9][\w\-\.\_]+)',re.I)
    >>> comment = stra.sub('ddd', comment)
    >>> print comment
    ddd ddd :请查看ddd 的文章

    好像是这么个思路!!
    paloalto
        4
    paloalto  
    OP
       Feb 1, 2013
    >>> stra = re.compile(r'@([a-zA-Z0-9][\w\-\.\_]+)',re.I)
    >>> comment = '@post-rocker @post-rocker'
    >>> for i in xrange(len(usernames)):
    ... comment = stra.sub('<a href="/member/'+ usernames[i] + '">' + nicknames[i] + '</a>', comment)
    ...
    >>> print comment
    <a href="/member/post-rocker">孬爷爷</a> <a href="/member/post-rocker">孬爷爷</a>


    大功告成!!!哈哈哈哈哈哈!!
    zhy0216
        5
    zhy0216  
       Feb 21, 2013
    用lz一开始的思路应该也走得通.
    只要去除重复就可以了.
    具体可以使用一个dictionary.
    dict(zip(usernames,nicknames))
    greenymora
        6
    greenymora  
       Feb 22, 2013
    @paloalto 话说。我想要进排名看看。邮箱是 [email protected]
    paloalto
        7
    paloalto  
    OP
       Feb 22, 2013
    @greenymora 排名已经停了啊。我从那个公司离职一年多了。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4941 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 64ms · UTC 09:52 · PVG 17:52 · LAX 02:52 · JFK 05:52
    ♥ Do have faith in what you're doing.