1

I'm newbie in Python. I have a text file like following:

"0","0","0","0","1","0"    
"0","0","0","2","1","0"
...

I want to import this text file as a matrix in Python. I can find examples similar to this, but they don't have quotation marks for each value so it doesn't work directly for this case. How I can read only numerical values from text and save it as a matrix?

Thanks

1
  • 1
    Use the csv library to read the file and cast each value to int while you're reading the rows. You could possibly just split each row on commas and cast to int, but if it's a CSV, you might as well use the built-in library. Commented Oct 26, 2018 at 2:21

1 Answer 1

1

A go to method for reading things into a list is the readlines() method for files. However, your data is a bit tricky since you have quotation marks. Note, these are not the usual quotation marks around a string declaration, but actual text.

We iterate through the values and remove them, then convert the remaining string to integer. We then append each row to a matrix:

with open('data.txt', 'r') as f:
    data = f.readlines() # read raw lines into an array

cleaned_matrix = [] 
for raw_line in data:
    split_line = raw_line.strip().split(",") # ["1", "0" ... ]
    nums_ls = [int(x.replace('"', '')) for x in split_line] # get rid of the quotation marks and convert to int
    cleaned_matrix.append(nums_ls)

print cleaned_matrix

output:

[[0, 0, 0, 0, 1, 0], 
 [0, 0, 0, 2, 1, 0]]
Sign up to request clarification or add additional context in comments.

Comments

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.