0

I'm new to python. I need to find the words in a list that contains these vowels using regular expressions. The following does not work. Can anyone see what needs to be corrected? Thank you.

import re
file = open('wordlist.txt', 'r')
print re.findall('[aie]', file)

I get this error:

Traceback (most recent call last):
    File "C:\Python27\MyScripts\script2.py", line 3, in ` <module>
        print re.findall('[aie]', file)
    File "C:\Python27\lib\re.py", line 181, in findall
        return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer

Here is what is in the wordlist, which I can retrieve by using this:

file = open('wordlist.txt', 'r')
print file.read()`

Prints out:

ae
The 
Intelligent 
Assistance 
Revolution 
may 
not 
be 
televised 
but 
it 
will 
definitely 
be 
2
  • 1
    Not that I knew Python, but it seems that findall expects a string, not a file... Commented Aug 13, 2015 at 10:09
  • Thanks for editing my question. I'll have to practice. This is my first question and could not get it to print correctly. Commented Aug 13, 2015 at 10:13

2 Answers 2

2

re.findall() doesn't accept a file object, as the error says you need to pass a string or buffer so you can use file.read() to pass the file as a string object to findall() function :

print re.findall('[aie]', file.read())

Or as a more pythonic way if you are dealing with huge files for refusing of reading the file at once, you can loop over your file and based on your need use re.search or re.fildall for each line.

with open('wordlist.txt') as f:
   for line in f:
      #do stuff with line
Sign up to request clarification or add additional context in comments.

3 Comments

thanks so much for the detail. I spent a lot of time trying to figure out the problem. Very new to python. thanks! I'm taking notes.
@angelica Welcome, so if you have found this answer helpful you can tell this to community by accepting the answer ;)
I immediately tried to accept the answer but I got a pop-up saying that I could not accept an answer til I got a reputation of 15 points! Since I just started, I could not do that. After I get 15 points, I will come back to this and accept it.
1

This should do it:

import re
file = open('wordlist.txt', 'r')
print re.findall('[aie]', file.read())

The error is due to the fact you are trying implement on a file object not it is content

2 Comments

thanks so much. I spent a lot of time trying to figure out the problem. Very new to python. thanks!
@angelica happy to help :)\

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.