简体   繁体   中英

Convert strings in a text file (already in tuple format) to list of tuples

I have a txt file, "first.txt," that looks like this:

(abc, bcd)

(cde, sos)

(feg, rof)

etc.

I also have another list (let's call this "second") that looks like this, already in tuple format (A tuple consisting of two strings):

('sos','ten')

('rof','bcd')

etc.

I want to compare these two lists and get the difference between them. To do so, I need "first.txt" to be converted to the same tuple format as my list, "second."

I tried doing some list comprehension and then converting the string to a tuple and splitting on "\\n", but that just gives ('(abc, bcd)', ''), whereas I want a tuple consisting of two strings.

Any suggestions?

if none of your text element conatin ( , ) , or , , you can use regular string function to "parse" the tuple, like this:

content = """\
(abc, bcd)
(cde, sos)
(feg, rof)
"""

result = [tuple(line.strip('()').split(",")) for line in content.splitlines()]

print(result)

Output:

[('abc', ' bcd'), ('cde', ' sos'), ('feg', ' rof')]

I know eval() is evil, but you can try this:

>>> lst = []
>>> with open('second.txt') as f:
...     for line in f:
...         lst.append(eval(line, {}, {}))
...         
>>> lst
[('sos', 'ten'), ('rof', 'bcd')]

Your first.txt is not really in a tuple of str format.

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