如何使用 set.union() 跟踪出现次数

How to track number of occurrences with set.union()

所以,我循环浏览了一堆文档,创建了文档中所有唯一单词和顺序单词组的列表(显然,我正在查看的字符串非常短)。

globallist=[]
for filename in glob.glob(os.path.join(path, '*.html')):
     mystr = "some text I want"
     stuff = re.sub("[^\w]", " ",  mystr).split()
     wordlist = [''.join(stuff[i:j]) for i in range(len(stuff)) for j in range(i+1, len(stuff)+1)]
     globallist = set.union(set(globallist), set(wordlist))

我想在执行过程中使用 globallist 跟踪出现的情况,这样到最后我已经可以计算出 有多少文档 包含列表中的每个字符串。我计划删除任何只出现在一个文档中的元素。执行此操作的最佳方法是什么?

为每个文档创建 set 个单词,并用每个文件的单词更新 collections.Counterset 每个文件避免对每个文件多次计算单词,Counter 无缝地跨文件求和。对于一个计算单个单词的超级简单示例(不跟踪它们来自哪个文件):

from collections import Counter

totals = Counter()
for file in allfiles:
    with open(file) as f:
        totals.update(set(f.read().split()))

下面的脚本应该有助于给您一些想法。

您正在尝试解析 HTML 个文件,因此理想情况下您只需要从每个文件中提取没有任何 HTML 标记的文本。这可以使用 BeautifulSoup 等库来完成。接下来,最好将所有单词都小写,以确保您使用不同的大小写来捕捉单词。 Python 的 collections.Counter 可以用来计算所有的单词,从中可以构建一个只包含单词且计数为 1 的列表。最后可以对您的短语进行计数。

然后所有这些信息都可以按文件存储到 file_stats 中。然后在最后显示结果。

由此,您将能够看到有多少文档包含您要查找的文本。

from bs4 import BeautifulSoup
import collections
import glob
import re   
import os

path = r'mypath'
file_stats = []

search_list = ['some text I want', 'some other text']
search_list = [phrase.lower() for phrase in search_list]    # Ensure list is all lowercase

for filename in glob.glob(os.path.join(path, '*.html')):
    with open(filename, 'r') as f_input:
        html = f_input.read()

    soup = BeautifulSoup(html, 'html.parser')

    # Remove style and script sections from the HTML
    for script in soup(["style", "script"]):
        script.extract() 

    # Extract all text
    text = soup.get_text().encode('utf-8')

    # Create a word list in lowercase
    word_list = [word.lower() for word in re.sub("[^\w]", " ",  text).split()]

    # Search for matching phrases
    phrase_counts = dict()
    text = ' '.join(word_list)

    for search in search_list:
        phrase_counts[search] = text.count(search)

    # Calculate the word counts
    word_counts = collections.Counter(word_list)

    # Filter unique words
    unique_words = sorted(word for word, count in word_counts.items() if count == 1)

    # Create a list of unique words and phrase matches for each file
    file_stats.append([filename, unique_words, phrase_counts])

# Display the results for all files
for filename, unique_words, phrase_counts in file_stats:
    print '{:30} {}'.format(filename, unique_words)
    for phrase, count in phrase_counts.items():
        print '  {} : {}'.format(phrase, count)