簡體   English   中英

計算html文件中的詞組頻率

[英]Counting phrase frequencies in an html file

我目前正在嘗試適應Python,最近在我的編碼中碰到了塊。 我無法運行用於計算短語在html文件中出現的次數的代碼。 我最近獲得了一些幫助來構建用於計算文本文件中頻率的代碼的幫助,但我想知道是否有一種方法可以直接從html文件中執行此操作(繞過復制和粘貼替代方法)。 任何建議將由衷的感謝。 我以前使用的編碼如下:

#!/bin/env python 3.3.2
import collections
import re

# Defining a function named "findWords".
def findWords(filepath):
  with open(filepath) as infile:
    for line in infile:
      words = re.findall('\w+', line.lower())
      yield from words

phcnt = collections.Counter()

from itertools import tee
phrases = {'central bank', 'high inflation'}
fw1, fw2 = tee(findWords('02.2003.BenBernanke.txt'))   
next(fw2)
for w1,w2 in zip(fw1, fw2):
  phrase = ' '.join([w1, w2])
  if phrase in phrases:
    phcnt[phrase] += 1

print(phcnt)

您可以使用some_str.count(some_phrase)函數

In [19]: txt = 'Text mining, also referred to as text data mining, Text mining,\
         also referred to as text data mining,'
In [20]: txt.lower().count('data mining')
Out[20]: 2

在進行分析之前僅剝離html標簽怎么辦? html2text可以很好地完成這項工作。

import html2text
content = html2text.html2text(infile.read())

會給您文本內容(以某種方式格式化,但是我認為這在您的方法中沒有問題)。 您還可以使用其他選項來忽略圖像和鏈接

h = html2text.HTML2Text()
h.ignore_images = True
h.ignore_links = True
content = h.handle(infile.read())

暫無
暫無

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

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