【问题标题】:get first paragraph from wikipedia article从维基百科文章中获取第一段
【发布时间】:2011-10-30 01:03:51
【问题描述】:

我正在使用以下代码从 Wikipedia 文章中获取第一段。这是result of my code。我只需要这一段。可能吗?或者有没有更好的选择?

'''Papori''' ({{lang-as|'''?????'''}}) 是一个 [[Assamese language]] 特征 [[Jahnu Barua]] 导演的电影。电影明星 Gopi Desai,[[Biju Phukan]], Sushil Goswami、Chetana Das 和 Dulal Roy。这部电影于 1986 年上映。

这是我的代码:

#!/usr/bin/python
from lxml import etree
import urllib
from BeautifulSoup import BeautifulSoup

class AppURLopener(urllib.FancyURLopener):
    version = "WikiDownloader"

urllib._urlopener = AppURLopener()
query = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&titles=papori&rvsection=0'
#data = { 'catname':'', 'wpDownload':1, 'pages':"\n".join(pages)}
#data = urllib.urlencode(data)
f = urllib.urlopen(query)
s = f.read()
#doc = etree.parse(f)
#print(s)
soup = BeautifulSoup(s)
secondPTag = soup.findAll('rev')
print secondPTag

代码更新:任何人帮助我删除{{ }} 之间的文本。因为没有必要。谢谢

【问题讨论】:

    标签: python xml wikipedia


    【解决方案1】:

    要删除从{{'''Papori''' 的所有内容:

    import re
    regex = re.compile(r"""{{.*?}}\s*('''Papori''')""", re.DOTALL)
    print regex.sub(r"\1", rev_data)
    

    要删除从第一个“{{”到匹配的“}}”的所有内容:

    prefix, sep, rest = rev_data.partition("{{")
    if sep: # found the first "{{"
        rest = sep + rest # put it back
        while rest.startswith("{{"):
            # remove nested "{{expr}}" one by one until there is none
            rest, n = re.subn(r"{{(?:[^{]|(?<!{){)*?}}", "", rest, 1)
            if n == 0: 
                break # the first "{{" is unmatched; can't remove it
        else: # deletion is successful
            rev_data = prefix + rest
    print(rev_data)
    

    要删除从第一个“{{”到匹配“}}”的所有内容,而不使用正则表达式:

    prefix, sep, rest = rev_data.partition("{{")
    if sep: # found the first "{{"
        depth = 1
        prevc = None
        for i, c in enumerate(rest):
            if c == "{" and  prevc == c:  # found "{{"
                depth += 1
                prevc = None # match "{{{ " only once
            elif c == "}" and prevc == c: # found "}}"
                depth -= 1
                if depth == 0: # found matching "}}"
                    rev_data = prefix + rest[i+1:] # after matching "}}"
                    break
                prevc = None # match "}}} " only once
            else:
                prevc = c
    print(rev_data)
    

    完整示例

    #!/usr/bin/env python
    import urllib, urllib2
    import xml.etree.cElementTree as etree
    
    # download & parse xml, find rev data
    params = dict(action="query", prop="revisions", rvprop="content",
                  format="xml", titles="papori", rvsection=0)
    request = urllib2.Request(
        "http://en.wikipedia.org/w/api.php?" + urllib.urlencode(params), 
        headers={"User-Agent": "WikiDownloader/1.0",
                 "Referer": "http://stackoverflow.com/q/7937855"})
    tree = etree.parse(urllib2.urlopen(request))
    rev_data = tree.findtext('.//rev')
    
    # remove everything from the first "{{" to matching "}}"
    prefix, sep, rest = rev_data.partition("{{")
    if sep: # found the first "{{"
        depth = 1
        prevc = None
        for i, c in enumerate(rest):
            if c == "{" and  prevc == c:  # found "{{"
                depth += 1
                prevc = None # match "{{{ " only once
            elif c == "}" and prevc == c: # found "}}"
                depth -= 1
                if depth == 0: # found matching "}}"
                    rev_data = prefix + rest[i+1:] # after matching "}}"
                    break
                prevc = None # match "}}} " only once
            else:
                prevc = c
    print rev_data
    

    输出

    '''Papori''' ({{lang-as|'''পাপৰী'''}}) is an [[Assamese
    language]] feature film directed by [[Jahnu Barua]]. The film
    stars Gopi Desai, [[Biju Phukan]], Sushil Goswami, Chetana Das
    and Dulal Roy. The film was released in 1986.<ref name="ab">{{cite
    web|url=http://www.chaosmag.in/barua.html|title=Papori – 1986 –
    Assamese film|publisher=Chaosmag|accessdate=4 February
    2010}}</ref>
    

    【讨论】:

    • 谢谢 但是文本是动态的。我想删除从{{}} 的所有内容。谢谢
    • @user559744:我添加了删除从第一个 "{{" 到匹配 "}}" 的所有内容的变体。
    【解决方案2】:

    是的,这是可能的。你可以使用像 HTMLParser 这样的 HTML 解析器,但我推荐 Beautiful Soup

    使用正则表达式删除子字符串,如下所示:

    >>> email = "tony@tiremove_thisger.net"
    >>> m = re.search("remove_this", email)
    >>> email[:m.start()] + email[m.end():]
    'tony@tiger.net'
    

    【讨论】:

    • 我用的是漂亮的汤。这很棒。但是我想删除{{ }} 之间的这段文字。我怎样才能删除?谢谢
    • @vivek:要删除 "remove_this",您可以使用:email.replace("remove_this", "")
    猜你喜欢
    • 1970-01-01
    • 2011-05-26
    • 2010-12-06
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    相关资源
    最近更新 更多