0

ERROR: Traceback (most recent call last): File "c:\Users\Pranjal\Desktop\tstp\zen_scraper.py", line 5, in words = re.findall("$y",file) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2288.0_x64__qbz5n2kfra8p0\lib\re.py", line 241, in findall return _compile(pattern, flags).findall(string) TypeError: expected string or bytes-like object PS C:\Users\Pranjal\Desktop\tstp>

import re

file = open("zen.txt",'r')

words = re.findall("$y",file)
print(words)

1 Answers1

0

You have opened the file but you haven't got its content yet. Also, re is not necessary here, str.endswith() is all you need.

with open("zen.txt",'r') as f:
    for line in f:
        for word in line.split():
            if word.endswith('y'):
                print(word)
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • how does python recognise "line" and "word" ????are these python in built keywords???@alec_djinn –  Mar 20 '21 at 15:09
  • 1
    @PranjalRuhela no, any variable name would do. f is a file object that you can think of it as a list of lines. So iterating over it give you the lines. Each line is a string made by words separated by spaces, .split() makes a list of words out of it. Check this https://docs.python.org/3/library/functions.html#open and https://docs.python.org/3/tutorial/inputoutput.html#tut-files – alec_djinn Mar 21 '21 at 06:07