2

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

2 回答 2

1

You can use some_str.count(some_phrase) function

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
于 2013-11-18T08:13:02.870 回答
0

在进行分析之前剥离 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())
于 2013-11-19T00:05:20.980 回答