user12839687
user12839687

Reputation:

Creating tuple from a text file

I want to create tuple like this:

(num_rows, num_columns, matrix)

example be:

   (3,5,[['o','x','o','x','o'], ['o','o','o','x','x'], ['o','o','o','o','o']])

Input from text file:

3 5
o x o x o
o o o x x
o o o o o

Some code I have tired so far:

  file_name = open('input_1.txt', 'r')
        inputs= []
        for line in file_name:
            input= ((line.split('\t')))
            inputs.append(input)
        file_name.close()

        return (tuple(inputs))

Upvotes: 2

Views: 330

Answers (4)

abhiarora
abhiarora

Reputation: 10460

Try this:

def getTuple():
    with open('file.txt', 'r') as file:
        result = []
        matrix = []
        result.extend(map(int, file.readline().split()))
        for line in file:
            matrix.append(line.split())
        result.append(matrix)
    return tuple(result)


print(getTuple())

Outputs:

(3, 5, [['o', 'x', 'o', 'x', 'o'], ['o', 'o', 'o', 'x', 'x'], ['o', 'o', 'o', 'o', 'o']])

However, your code was returning:

(['3 5\n'], ['o x o x o\n'], ['o o o x x\n'], ['o o o o o'])

Let me walk you though the logic behind possible implementation (The points also point out the issues in your code):

  1. You need to read/treat the first line differently than the rest of the lines in your file (it contains the number of rows and columns). You need to split the first line using split() method (without any argument passed to it, see this to know what difference it makes) and then use map() to convert each element in the first line to int. The object returned by map() (map object in Python 3.x) (See this to learn more about map) is used to extend the list result.

  2. Other lines needs to be split using split() and then appended to a list matrix. After the end of the for loop, we can append the matrix to the list result.

  3. See this to learn more about syntax used by me to manage the file resource (with open('file.txt', 'r') as file).

Upvotes: 3

djoguns
djoguns

Reputation: 96

Sample Input Text: "input_1.txt"

o x o x o x
o o o x x x
o o o o o x
o o o x x x
o o o o o x
o o o x x x
o o o o o o
o o o x x x

Solution:

def create_matrix_tuple(file_name):
    """
    l. Loads the text file
    2. Initialises empty content of the file
    3. Get the length of rows and length of columns
    """
    # Reads in the data
    file_name = open("input_1.txt", "r")

    # initialises input content with empty list
    output = []

    # Loop over every line of the content
    line_text = file_name.read().splitlines()
    for line in line_text:
        output.append(
            list(
                line.replace(" ", "")
            )
        )        
    num_rows, num_cols = len(output), len(output[0])

    return (num_rows, num_cols, output)

if __name__ == "__main__" :
    desired_output = create_matrix_tuple(file_name)    
    print(desired_output)

Upvotes: 0

Carlo 1585
Carlo 1585

Reputation: 1477

Maybe this is not the best solution but it give you the expected output:

Input:

3 5
o x o x o
o o o x x
o o o o o

I made some change to your code:

file_name = open('input_1.txt', 'r')
tmp= []
for line in file_name:
    input= ((line.split('\n'))) 
    #you split the line by \n so each line is a different list of 1 element in order 0
    input = input[0].split(" ")
    # you split each element of the list seeing that u have only one by space
    tmp.append(input)
file_name.close()


inputs = [tmp[0][0], tmp [0][1], tmp[1:]] 
#seeing that you want the first two values out of the sublist you rework it in the needed format
print inputs

This is the output:

['3', '5', [['o', 'x', 'o', 'x', 'o'], ['o', 'o', 'o', 'x', 'x'], ['o', 'o', 'o', 'o', 'o']]]

Upvotes: 0

Zaraki Kenpachi
Zaraki Kenpachi

Reputation: 5740

file_name = open('data.txt', 'r')


def generate_tuple(file_name):
    data = []
    for line in file_name.read().splitlines():
        data.append(list(line.replace(" ", "")))

    out = (len(data),len(data[0]), data)
    return out

Output:

(3, 5, [['o', 'x', 'o', 'x', 'o'], ['o', 'o', 'o', 'x', 'x'], ['o', 'o', 'o', 'o', 'o']])

Upvotes: 2

Related Questions