0

I have this:

fin = open(blah)
fin_lower= fin.readlines()
lines = [fin_lower.lower() for line in fin]
lines = line.split()

It gives:

TypeError: expected string or buffer

Is it wrong to readlines?

3 Answers 3

1

readlines returns a list containing all lines of data, it looks like you have a bug, and you probably want to do this:

lines = [line.lower() for line in fin_lower]

Your code is also mixing variables around, take a good step through it, what are you trying to accomplish? You seem to mix line and lines a bunch.

Sign up to request clarification or add additional context in comments.

1 Comment

Right, you have a problem there, what exactly are you trying to do with that statement?
1

re.sub expects a string as the third argument, you gave it lines which is a list. Also, you're iterating over fin after consuming all lines of it with readlines. You seem to be trying to do:

with open(blah) as fin:
    lines = [line.lower().replace(',', '').split() for line in fin]

Also note that you don't need re to do a literal replacement.

4 Comments

@NantiaDiko Yep, I added a call of lower(). Forgot it at first.
@NantiaDiko Because lines is now a list of lists because of split(). You can try printing things to understand what's going on in your script.
@NantiaDiko Indeed, strings don't have a remove method, lists do. How can I help?
@NantiaDiko Don't get me wrong, but this is becoming a little unconstructive. I suggest that you: 1) read a tutorial about Python's standard data types; 2) play with them in an interactive Python interpreter of your choice. You'll see how split and startswith work with strings and how remove and for loops work with lists.
0

I agree with Bartek

I was able to get this done.

import os
import signal
import time
import sys
import re
import string

fin = open('blah','r')
fin_lower= fin.readlines()

lines=""

for line in fin_lower:
lines += line.lower()


line = re.sub(';',' ',lines)
lines = line.split()
print lines

Initial Contents of File blah

VISHAL; KHIALANI; NONOE; CANGETITDONE;

Final Output

['vishal', 'khialani', 'nonoe', 'cangetitdone']

Comments

Your Answer

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