【问题标题】:Counting phrase frequencies in an html file计算 html 文件中的短语频率
【发布时间】:2013-11-18 07:35:44
【问题描述】:

我目前正在尝试习惯 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)

【问题讨论】:

  • 你可以使用collections.Counter
  • @Ashish Nitin Patil:不幸的是,这只能让我计算单词,而不是短语

标签: python html frequency phrase


【解决方案1】:

你可以使用 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 文件上使用它。
【解决方案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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多