简体   繁体   中英

Reading a txt file of a tuple of a list and an int

What would be an effective way to read in lines that are tuples of a list and an int?

Each line in the txt file should look like this:

([1, 2, 3, 4, 5, 6], 1)

The first thing that came to mind was to use .split('],') , but how do I process the tuple next?

Thank you!

Given that a line has been read in,

s = ([1, 2, 3, 4, 5, 6], 1)

We first will need to parse the tuple parenthesis. Based off the wording of your question, my understanding is that there is only one tuple per line. Therefore we can use string splicing to remove the outside parenthesis first.

s = s[1:len(s) - 1]

Giving us, [1, 2, 3, 4, 5, 6], 1

Next we want to split the list from the int. You are on the right track with splitting the string using ], as a delimiter, however in that case we would be left with,

['[1, 2, 3, 4, 5, 6', ' 1']

A similar but slightly different approach would be to use regular expressions and split only on , which are directly proceeded by ] We will use the Positive Lookbehind technique to achieve this.

import re
s = s[1:len(s) - 1]
regex = '(?<=]), '
results = re.split(regex, s)

Now results will be a list of two values,

  1. A string representation of our list, [1, 2, 3, 4, 5, 6]
  2. Our integer value 1 as a string

Finally to split and use our tuple values we will use similar methods.

  1. Remove opening and closing brackets by splicing
  2. Split remaining string using , as a delimiter

As shown here,

listResult = results[0]
listResult = listResult[1:len(listResult) - 1]
listResult = listResult.split(', ')

Lastly, our integer value can obtained by accessing results list at index 1 ,

intResult = results[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM