crawl4ai icon indicating copy to clipboard operation
crawl4ai copied to clipboard

fix: use str.split() for accurate word count in PruningContentFilter

Open karesansui-u opened this issue 8 months ago • 1 comments

Summary

_compute_composite_score() uses text.count(" ") + 1 to count words, which overcounts when consecutive spaces are present. HTML-extracted text from get_text(strip=True) commonly contains multiple consecutive spaces between inline elements — each extra space inflates the count by one, making min_word_threshold checks too lenient and allowing short/noisy nodes to survive pruning.

Before (line 742):

word_count = text.count(" ") + 1

After:

word_count = len(text.split())

The same file already uses len(text.split()) for the identical purpose at line 268 and line 302, so this change also restores internal consistency.

Edge case

text.count(" ") + 1 returns 1 for an empty string, while len("".split()) correctly returns 0. This means empty-text nodes that should be removed by min_word_threshold >= 1 currently slip through.

Changed files

  • crawl4ai/content_filter_strategy.py — 1 line in _compute_composite_score()

Testing

Verified that str.split() handles consecutive spaces, tabs, and empty strings correctly:

>>> "hello     world".count(" ") + 1   # overcounts
6
>>> len("hello     world".split())       # correct
2
>>> "".count(" ") + 1                    # wrong for empty
1
>>> len("".split())                      # correct
0

karesansui-u avatar Mar 16 '26 16:03 karesansui-u

Hi @karesansui-u — this fix is correct and the root cause analysis is spot on.

Since this PR had been open without review for 6 weeks, I filed it as PR #1935 with an associated test suite (17 targeted tests covering empty strings, consecutive spaces, tabs, whitespace-only nodes, and integration with min_word_threshold). Your work is credited in the PR description.

Thanks for catching this — the inconsistency with lines 268 and 302 was a great catch.

hafezparast avatar Apr 24 '26 03:04 hafezparast