从字符串开头删除连续字符

2024-09-27 22:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

最好的办法是去掉维基百科参考文献开头的字母顺序?在

例如,从

a b c d Star Wars Episode III: Revenge of the Sith (DVD). 20th Century Fox. 2005.

Star Wars Episode III: Revenge of the Sith (DVD). 20th Century Fox. 2005.

我想出了一个可行的解决方案,但似乎很笨拙。我的版本使用的正则表达式形式为'^(?)?:a(?)?:b(?)?:c)?)?)?'。什么是正确的,快速的方法?在

a = list('abcdefghijklmnopqrstuvwxyz')
reg = "^%s%s" % ( "".join(["(?:%s " %b for b in a]), ")?"*len(a) )
re.sub(reg, "", "a b c d Wikipedia Reference")

Tags: ofthe字母reg参考文献stariiidvd
3条回答

如果你是复制和粘贴网页文本而不是处理html,一些问题中提到的问题是不可避免的。但是,使用htmllib处理html(如下所示的相关行),您可以将<sup><i><b>c</b></i></sup>(它提供c)之类的项作为单位删除。[编辑:我现在看到htmllib已被弃用;我不知道合适的替代品,但相信它是HTMLParser。]

显示的行有点像

^ abcdeStar Wars: Episode III Revenge of the Sith DVD commentary featuring George Lucas, Rick McCallum, Rob Coleman, John Knoll and Roger Guyett, [2005]

这行的html源代码是

<li id="cite_note-DVDcom-13"><span class="mw-cite-backlink">^ <a href="#cite_ref-DVDcom_13-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-DVDcom_13-1"><sup><i><b>b</b></i></sup></a> <a href="#cite_ref-DVDcom_13-2"><sup><i><b>c</b></i></sup></a> <a href="#cite_ref-DVDcom_13-3"><sup><i><b>d</b></i></sup></a> <a href="#cite_ref-DVDcom_13-4"><sup><i><b>e</b></i></sup></a></span> <span class="reference-text"><i>Star Wars: Episode III Revenge of the Sith</i> DVD commentary featuring George Lucas, Rick McCallum, Rob Coleman, John Knoll and Roger Guyett, [2005]</span></li>

在正则表达式中使用字符类如何,即:

re.sub('^([a-z] )*', '', ...)

这将删除单个字母字符后面跟一个空格的任何数量的前导出现。在

我可能会做这样的事情:

title = re.sub(r'^([a-z]\s)*', '', 'a b c d Wikipedia Reference')

和你现在的情况一样。然而,正如@joran beasley指出的,对于复杂的案件,你可能需要更聪明的东西。在

相关问题 更多 >

    热门问题