-1

I want to use re.findall for detecting how many times is a a word displayed in a .txt file. Also I need that if I'm trying to count how many times the word Hello appears in the text Hellooo to be detected.

Here is all the code I have:

# -*- coding: utf-8 -*-
import re

total = 0

with open('text.txt') as f:
    for line in f:
        total = re.findall('Hello')

print total
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Markel
  • 65
  • 1
  • 6
  • It looks like your forgot to ask a question in your question. Please red [ask] and provide a [MCVE]. – timgeb Mar 25 '18 at 13:18

2 Answers2

4

Why even use regex?

The count() method would do the same thing:

with open('text.txt') as f:

    total = f.read()
    print total.count('Hello')

And does not require importing modules, since it is inbuilt.

When using regex also not it is advisable to use r as a raw string prefix. total = re.findall(r'Hello')

Xantium
  • 11,201
  • 10
  • 62
  • 89
3

Creating a file:

echo "Hellooo there.
Hello hello Hello" > file.txt

And finding all occurrences of "Hello":

In [1]: import re

In [2]: with open('file.txt') as f:
   ...:     all_hellos = re.findall('Hello', f.read())
   ...:

In [3]: print(len(all_hellos))
3

The above will only look for Hello but not hello. And this will cache the entire file in memory, so this will be fine unless you are using big files.

Remember re.findall() will return a list of all occurrences found, not the number of occurrences.

Robert Seaman
  • 2,432
  • 15
  • 18
  • 2
    Why not simply use `str.count` if you don't use `re.finditer` for memory efficiency? – timgeb Mar 25 '18 at 13:20
  • @timgeb str.count looks nice. I never knew about that. I didn't know if the user was looking to use `re.findall` specifically. – Robert Seaman Mar 25 '18 at 13:22