【发布时间】: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