简体   繁体   English

将文本文件中的字符串(已经以元组格式)转换为元组列表

[英]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: 我有一个txt文件“ first.txt”,看起来像这样:

(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." 为此,我需要将“ first.txt”转换为与列表“ 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. 我尝试做一些列表理解,然后将字符串转换为元组并在“ \\ n”上分割,但这仅给出了('(abc,bcd)',''),而我想要一个由两个字符串组成的元组。

Any suggestions? 有什么建议么?

if none of your text element conatin ( , ) , or , , you can use regular string function to "parse" the tuple, like this: 如果您的文本元素都不是conatin ( ),则可以使用常规字符串函数来“解析”该元组,如下所示:

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: 我知道eval()是邪恶的,但是您可以尝试执行以下操作:

>>> 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. 您的first.txt并非真正采用str格式的tuple

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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