7beggars_nnnnm
7beggars_nnnnm

Reputation: 777

Inside python code read file directly and apply module regex

I have the following python-regex read.py file modified below from this question. In the same directory I have another text file called 1.txt.

read.py

import re
with open ("1.txt", "r") as text:
    data = text.read()
print( re.sub(r"(.)\1*", lambda x: "{}{}".format( x.group(1), len(x.group())),  text) )

1.txt

UUBBBRRLLLBBBDDD

I am trying to read the contents of 1.txt into text in the read.py structure and then get the same result as if I had inserted the text into the read2.py code (see below).

read2.py

import re
text = "UUBBBRRLLLBBBDDD"
print( re.sub(r"(.)\1*", lambda x: "{}{}".format( x.group(1), len(x.group())),  text) )

But if I run read.py I always get the following error:

Traceback (most recent call last):
  File "axios.py", line 5, in <module>
    print( re.sub(r"(.)\1*", lambda x: "{}{}".format( x.group(1), len(x.group())),  text) )
  File "/usr/lib/python3.8/re.py", line 208, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

I understand that I should read 1.txt as a variable and then read it in the excerpt print( re.sub(r"(.)\1*", lambda x: "{}{}".format( x.group(1), len(x.group())), text) ) from read.py.

But I don't understand why I didn't read it and it was resulting in an error and I can't read the file directly from read.py and get the same result in read1.py. I already googled it and haven't found anything involving module regex, read and print together in the same python file as they should work in read.py.

Upvotes: 2

Views: 173

Answers (1)

Mr.C
Mr.C

Reputation: 162

Shouldn't the "text" variable just be "data"? This works: print(re.sub(r"(.)\1*", lambda x: "{}{}".format(len(x.group()), x.group(1)), data))

"text" is a <class '_io.TextIOWrapper'> (i.e. a file-like object) that is read from and then closed, whereas "data" is the variable that holds a reference to a string.

Upvotes: 2

Related Questions