是否有功能可以将这种文本文件格式转换为二维列表?

时间:2019-08-09 00:11:16

标签: python python-3.x

这是我的文本文件的示例:

太阳的第一个行星是什么? :水星
太阳的第二个行星是什么? :金星
太阳的第三个行星是什么? :地球

我正在尝试找到一种有效的方法来调用可以从每一行进行分析的问题和答案。我的想法是将其转换为列表,然后转换为2d列表,但是我尝试的每种方法均不可用。关于如何执行此操作的任何想法?

import re

f = open("C:/Users/PatrickStar/Desktop/Trivia_practice.txt", "r")
file_contents = f.read()
file_contents = file_contents.split("\n")

print(file_contents[0])
f.close()

2 个答案:

答案 0 :(得分:1)

您可以使用列表理解功能对冒号进行拆分,并创建一个嵌套列表

file_contents = file_contents.split("\n")
# ['What is the 1st planet from the sun? :Mercury', 'What is the 2nd planet from the sun? :Venus', 'What is the 3rd planet from the sun? :Earth']
file_contents = [x.split(':') for x in file_contents]
# nested list where file_contents[i][0] is question and file_contents[i][1] is answer
# [['What is the 1st planet from the sun? ', 'Mercury'], ['What is the 2nd planet from the sun? ', 'Venus'], ['What is the 3rd planet from the sun? ', 'Earth']]

编辑:如果您不熟悉列表,则无需列表理解

file_contents = file_contents.split("\n")
# ['What is the 1st planet from the sun? :Mercury', 'What is the 2nd planet from the sun? :Venus', 'What is the 3rd planet from the sun? :Earth']
2d_contents = []
for x in file_contents:
    2d_contents.append(x.split(':'))
file_contents = 2d_contents
# nested list where file_contents[i][0] is question and file_contents[i][1] is answer
# [['What is the 1st planet from the sun? ', 'Mercury'], ['What is the 2nd planet from the sun? ', 'Venus'], ['What is the 3rd planet from the sun? ', 'Earth']]

答案 1 :(得分:0)

除了注释中建议的解决方案之外,您还可以避免显式的close调用以及使用withreadlines来解析行的需要:

with open("trivia_practice.txt", "r") as f:
    qa = [line.rstrip().split(" :") for line in f.readlines()]