Reputation: 1
Trying to decode some RLE text but I'm not sure how to do it via accessing the file, any ideas?
First I tried running the code with manually inputted string, worked fine, but whenever I try to access the file to read it and decode the RLE it doesn't seem to work.
def decode(m_str):
number = ''
ret_str = ''
for index in range(len(m_str)):
try:
int(m_str[index])
check = True
except ValueError:
check = False
if check:
number += m_str[index]
else:
ret_str += int(number)*m_str[index]
number = ''
return ret_str
f = open("RLE.txt", 'r')
read = f.read()
x = (read)
y = decode(x)
print(y)
If the content of the file is "5S4F8S"
I expect it to output
SSSSSFFFFSSSSSSSS
Instead, I get the error:
ValueError: invalid literal for int() with base 10: ''
Upvotes: 0
Views: 184
Reputation: 77875
Put in some basic debugging print
commands:
def decode(m_str): number = '' ret_str = ''
for index in range(len(m_str)):
try:
int(m_str[index])
check = True
except ValueError:
check = False
print(index, check, number)
if check:
number += m_str[index]
else:
ret_str += int(number)*m_str[index]
number = ''
return ret_str
f = open("RLE.txt", 'r')
read = f.read()
x = (read)
print(x, [ord(c) for c in x])
y = decode(x)
print(y)
Output:
5S4F8S
[53, 83, 52, 70, 56, 83, 10]
0 True
1 False 5
2 True
3 False 4
4 True
5 False 8
6 False
Traceback (most recent call last):
File "so.py", line 27, in <module>
y = decode(x)
File "so.py", line 16, in decode
ret_str += int(number)*m_str[index]
ValueError: invalid literal for int() with base 10: ''
Your problem is quite simple: your input includes a non-printing character, such as the "newline" and the end of the input. That's not a legal item to convert.
To fix this, clean the input:
x = (read).strip()
This will allow you to get the desired output.
I'll leave the other improvements to you.
Upvotes: 1