簡體   English   中英

python如何逐行計算html中的單詞數

[英]python how to count the number of words in html line by line

我想執行簡單的標記化以逐行計算html中的單詞數,除了<a>標記之間的單詞和<a>標記之間的單詞將單獨計數

nltk可以這樣做嗎? 還是有圖書館可以做到這一點?

例如:這是html代碼

<div class="side-article txt-article">
<p><strong>BATAM.TRIBUNNEWS.COM, BINTAN</strong> - Tradisi pedang pora mewarnai serah terima jabatan pejabat di <a href="http://batam.tribunnews.com/tag/polres/" title="Polres">Polres</a> <a href="http://batam.tribunnews.com/tag/bintan/" title="Bintan">Bintan</a>, Senin (3/10/2016).</p>
<p>Empat perwira baru Senin itu diminta cepat bekerja. Tumpukan pekerjaan rumah sudah menanti di meja masing masing.</p>
<p>Para pejabat tersebut yakni AKP Adi Kuasa Tarigan, Kasat Reskrim baru yang menggantikan AKP Arya Tesa Brahmana. Arya pindah sebagai Kabag Ops di <a href="http://batam.tribunnews.com/tag/polres/" title="Polres">Polres</a> Tanjungpinang.</p>

我希望輸出將是

WordsCount : 0 LinkWordsCount : 0
WordsCount : 21 LinkWordsCount : 2
WordsCount : 19 LinkWordsCount : 0
WordsCount : 25 LinkWordsCount : 2

WordsCount是除<a>標記之間的文本外,每行中的單詞數。 如果一個單詞出現兩次,將被視為兩個。 LinkWordsCount是<a>標記之間的單詞數。

因此,如何使它除<a>標記外逐行計數,並且<a>標記之間的單詞將單獨計數。

謝謝。

遍歷原始HTML的每一行,然后簡單地搜索每一行中的鏈接。

在下面的示例中,我使用一種非常幼稚的方式來獲取單詞計數-用空格分隔行(這種方式-被視為單詞,而BATAM.TRIBUNNEWS.COM視為單個單詞)。

from bs4 import BeautifulSoup

html = """
<div class="side-article txt-article">
<p><strong>BATAM.TRIBUNNEWS.COM, BINTAN</strong> - Tradisi pedang pora mewarnai serah terima jabatan pejabat di <a href="http://batam.tribunnews.com/tag/polres/" title="Polres">Polres</a> <a href="http://batam.tribunnews.com/tag/bintan/" title="Bintan">Bintan</a>, Senin (3/10/2016).</p>
<p>Empat perwira baru Senin itu diminta cepat bekerja. Tumpukan pekerjaan rumah sudah menanti di meja masing masing.</p>
<p>Para pejabat tersebut yakni AKP Adi Kuasa Tarigan, Kasat Reskrim baru yang menggantikan AKP Arya Tesa Brahmana. Arya pindah sebagai Kabag Ops di <a href="http://batam.tribunnews.com/tag/polres/" title="Polres">Polres</a> Tanjungpinang.</p>
"""

soup = BeautifulSoup(html.strip(), 'html.parser')

for line in html.strip().split('\n'):
    link_words = 0

    line_soup = BeautifulSoup(line.strip(), 'html.parser')
    for link in line_soup.findAll('a'):
        link_words += len(link.text.split())

    # naive way to get words count
    words_count = len(line_soup.text.split())
    print ('WordsCount : {0} LinkWordsCount : {1}'
           .format(words_count, link_words))

輸出:

WordsCount : 0 LinkWordsCount : 0
WordsCount : 16 LinkWordsCount : 2
WordsCount : 17 LinkWordsCount : 0
WordsCount : 25 LinkWordsCount : 1

編輯

如果要從文件中讀取HTML,請使用以下內容:

with open(path_to_html_file, 'r') as f:
    html = f.read()

我會建議嘗試用正則表達式去蟒蛇是

要計算鏈接文字中使用正則表達式是數HREF =像這樣一個

RegEx還可以幫助您查找不包含<>的單詞,並用空格將它們分開,您將可以得到一個數組,該數組可以擴展並且可以包含多個單詞。

那就是我要走的路。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM