2010-06-25 145 views
1

我需要幫助python編程: 我需要一個命令,可以搜索文本文件中標籤之間的所有單詞。例如 在文本文件中有<concept> food </concept>。我需要搜索<concept></concept>之間的所有單詞並顯示它們。 任何人都可以幫忙.......蟒蛇搜索標籤

回答

3
  1. 將文本文件加載到一個字符串中。
  2. 使用pos2 = s.find('</concept>', pos1)

你所尋求的話是那麼s[pos1+len('<concept>'):pos2]

+1

這種方法沒有考慮註釋和標記與空格考慮如果問題的作者暗示XML – nkrkv 2010-06-25 07:21:53

+0

+1爲了簡單 – jensgram 2010-06-25 07:22:42

1

看一看正則表達式搜索使用pos1 = s.find('<concept>')

  • 搜索<concept>中第一次出現的字符串</concept>http://docs.python.org/library/re.html

    如果你想有例如標籤<i>,嘗試

    text = "text to search. <i>this</i> is the word and also <i>that</i> end" 
    import re 
    re.findall("<i>(.*?)</i>",text) 
    

    這裏有一個簡短的說明的findall是如何工作的:它看起來對於一個給定的正則表達式給出的字符串中。正則表達式是<i>(.*?)</i>

    • <i>表示剛開始標記<i>
    • (.*?)創建組和匹配儘可能直到它的第一
    • </i>,其總結了標籤

    請注意,上述解決方案沒有類似於

    <i> here's a line 
    break </i> 
    

    既然你只是想提取單詞

    但是,當然也可以這樣做:

    re.findall("<i>(.*?)</i>",text,re.DOTALL) 
    
  • 3

    沒有爲HTML/XML一個偉大的圖書館中橫過命名BeautifulSoup。有了它:

    from BeautifulSoup import BeautifulStoneSoup 
    soup = BeautifulStoneSoup(open('myfile.xml', 'rt').read()) 
    for t in soup.findAll('concept'): 
        print t.string