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