使用python正则表达式计算文档中单词的频率

jen*_*001 5 python regex dictionary frequency count

创建了一个python模块,它读取文件,删除停用词并输出一个python字典,其中包含单词及其频率(文档中出现的次数).

def run():
filelist = os.listdir(path)
regex = re.compile(r'.*<div class="body">(.*?)</div>.*', re.DOTALL | re.IGNORECASE)
reg1 = re.compile(r'<\/?[ap][^>]*>', re.DOTALL | re.IGNORECASE)
quotereg = re.compile(r'&quot;', re.DOTALL | re.IGNORECASE)
puncreg = re.compile(r'[^\w]', re.DOTALL | re.IGNORECASE)
f = open(stopwordfile, 'r')
stopwords = f.read().lower().split()
totalfreq = {}

filewords = {}
htmlfiles = []
for file in filelist:
    if file[-5:] == '.html':
        htmlfiles.append(file)

for file in htmlfiles:
    f = open(path + file, 'r')
    words = f.read().lower()
    words = regex.findall(words)[0]
    words = quotereg.sub(' ', words)
    words = reg1.sub(' ', words)
    words = puncreg.sub(' ', words)
    words = words.strip().split()

    for w in stopwords:
        while w in words:
            words.remove(w)

     freq = {}
    for w in words:
       if w in freq:
           totalfreq[w] = totalfreq[w] + 1
           freq[w] = freq[w] + 1
       else:
           totalfreq[w] = 1
           freq[w] = 1
           filewords[file] = freq


    print totalfreq
Run Code Online (Sandbox Code Playgroud)

这将打印该文件中的所有"不间断"单词以及它们在文件中出现的频率:输出如下所示:

{{'星期六':1,'爱尔兰':1,'家庭':1,'给':1,'年':2,'周末':1,'史蒂夫':1,'客人':1, '问题':1,'在':2,'努力':1,'伙伴':1,'灭绝':1,'连衣裙':1,'儿童':4,'utans':1,'27 ':1,'加注':1,'衣柜':1,'发型':2,'制造':1,'humphreys':1,'亲戚':1,'动物园':5,'濒临灭绝': 1,'星期日':1,'特殊':1,'回答':1,'公开':1,'意识':1,'计划':1,'活动':1,'rhiona':1, '猩猩':4,'计划':1,'leonie':1,'orang':1,'昨天':2,'自由':2,'手':1,'狂野':1,'独立':1,'part':1,'准备':1,'透露':1,'天':1,'男人':1,'图片':1,'keane':1,'动物': 1,'14':1,'kevin':1,'16':1,'32':1,'age':1,'sibu':1,'dublin':2,'keepers':1, 'face':1,'mujur':1,'red':2,'orangutan':1,'species':1,'entry':1,'努力':1,'显示':1,'上午11点':1,'涌入':1,'3pm':1}

{'最新':1,'出生':2,'orang':1,'月':1,'史蒂夫':1,'问题':1,'utans':1,'孩子':4,'员工':1,'风头':1,'27':1,'基于':1,'关注':1,'星期日':1,'3pm':1,'终于':1,'4' :1,'maeve':1,'意识':1,'给':1,'活动':1,'长颈鹿':1,'facebook':1,'准备':1,'背景':1 ,"培育":1,'日':1,'登场':1,'rothschild':1,'repers':1,'电子邮件':1,'步骤':1,'上午11点':1,' page':1,'picture':1,'born':1,'result':1,'year':2,'saturday':1,'special':1,'closet':1,'haired' :2,'section':1,'bennet':2,'妈妈':3,'mujur':1,'条件':1,'公共':1,'红色':2,'显示':1 ,'orangutans':4,'自由':2,'守护者':1,'11月':1,'关心':1,'发送':1,'伟大':1,'起源':1,' 32':1,'邀请':1,'都灵':2,'计划':1,'猩猩':1,'努力':1,'涌入':1,'命名':1,'家庭' :1,'喜欢':1,'天气':1,'客人':1,'灭绝':1,'发布':1,'留下深刻印象':1,'加注':1,'透露':1 ,'保留 d':1,'humphreys':1,'自信':1,'小腿':3,'入口':1,'shane':1,'part':1,'helen':1,'注意' :1,'努力':1,'案例':1,'制作':2,'动物':1,'14':1,'16':1,'ms':1,'野':1 ,'savanna':1,'爱尔兰':1,'给':1,'居民':1,'建议':1,'滑':1,'在':2,'伙伴':1,'打扮':1,'种类':1,'kevin':1,'rhiona':1,'make':1,'zoo':3,'濒临灭绝':1,'亲戚':1,'回答' :1,'差':1,'独立':1,'计划':1,'leonie':1,'时间':1,'昨':1,'手':1,'hickey':1 ,'周末':1,'男':1,'sibu':1,'年龄':1,'稳定':2,'面子':1,'禁闭':1,'非洲':2,'条目':1,'keane':1,'clarke':2,'left':1}

但我需要将两个总数从两个文件或大量文件中加在一起,以便在所有文件中给出单词的总数,例如"zoo".第1档动物园= 5第2档动物园= 3总计= 8.

我似乎无法弄清楚我如何计算许多文件的单词,而不是一次只计算一个.

有任何想法吗?!

eyq*_*uem 3

中的反斜杠'<\/?[ap][^>]*>'没有用,因为'/'不是特殊字符

'[^\w]''\W' 顺便说一句会'[^\w]+'比只有一个更有效率'[^\w]'

re.DOTALL没有用,r'<\/?[ap][^>]*>'因为这个 RE 中没有点

如果你确实words = f.read().lower()要降低字母,则不需要re.IGNORECASE

用于替换的 RE 可以放入一个 RE 中: reg123 = re.compile(r'(</?[ap][^>]*>|&quot;|\W+)')

file不是一个好的文件名,它会覆盖现有内置函数的名称

将获取htmfiles的代码行替换为生成器表达式会更好

我不明白为什么'[0]'words = regex.findall(words)[0]

您还可以将 RE 中的停用词分组,用于替换为' '

stopwords = '|'.join(f.read().lower().split())
Run Code Online (Sandbox Code Playgroud)

包含在 RE 中进行替换

的缩进filewords[file] = freq 不好

我建议您进行以下改进;我没有测试它,因为我不是要处理的文件。它当然并不完美。有不清楚的地方请教。

def run():

    from collection import difaultdict

    with open(stopwordfile, 'r') as f:
        stopwords = '|'.join(f.read().lower().split())

    regex = re.compile(r'.*<div class="body">(.*?)</div>.*', re.DOTALL)
    reg123 = re.compile(r'(</?[ap][^>]*>|&quot;|\W+|'+stopwords+')')

    totalfreq = defaultdict(int)
    filewords = {}

    for filename in (fn for fn in os.listdir(path) if fn[-5:] == '.html'):
        with open(path + filename, 'r') as f:
            ch = regex.findall(f.read().lower())[0]
            ch = reg123.sub(' ', ch)
            words = ch.strip().split()

        freq = defaultdict(int)
        for w in words:
            totalfreq[w] += 1
            freq[w] += 1
        filewords[filename] = freq

    print totalfreq
Run Code Online (Sandbox Code Playgroud)

我不太明白你的问题。请给出精度