读取 python 中的文本文件并从中创建两个列表
Reading a text file inn python and creating two lists out of it
我有一个包含对话的文本文件
person 1: "quotes"
person 2:"quotes2"
.
.
.
person 1:"quotes 3"
person 2:"quotes 4"
我想读一读每个人的名言,把它放在一个列表中,然后再次保存为文本文件。还有另一个不同的列表,用于保存第 2 个人的名言和另一个不同的文件。我如何使用 python 给出每个引号可能是一行或多行?
您可以创建一个字典,其中键是作者的名字,值是他们引用的列表。我会使用 defaultdict
让事情变得更容易。使用字典的一个好处是您可以拥有未知数量的作者。
from collections import defaultdict
filename = "your_path.txt"
# This is a dictionary of lists
quotes = defaultdict(list)
with open(filename) as f:
lines = f.readlines()
index = 0
while index < len(lines):
try:
author, quote = lines[index].strip().split(':')
# If it doesn't end in quote, keep reading until it does
while not quote[-1] == '"':
index += 1
quote += "\n" + lines[index].strip()
quotes[author].append(quote.strip('"'))
except ValueError:
pass
index += 1
for key, value in quotes.items():
print(f"{key}: {value}")
输出类似于
person 1: ['quotes', 'quotes 3']
person 2: ['quotes2', 'quotes 4']
您可以修改为写入文件而不是控制台。
我有一个包含对话的文本文件
person 1: "quotes" person 2:"quotes2" . . . person 1:"quotes 3" person 2:"quotes 4"
我想读一读每个人的名言,把它放在一个列表中,然后再次保存为文本文件。还有另一个不同的列表,用于保存第 2 个人的名言和另一个不同的文件。我如何使用 python 给出每个引号可能是一行或多行?
您可以创建一个字典,其中键是作者的名字,值是他们引用的列表。我会使用 defaultdict
让事情变得更容易。使用字典的一个好处是您可以拥有未知数量的作者。
from collections import defaultdict
filename = "your_path.txt"
# This is a dictionary of lists
quotes = defaultdict(list)
with open(filename) as f:
lines = f.readlines()
index = 0
while index < len(lines):
try:
author, quote = lines[index].strip().split(':')
# If it doesn't end in quote, keep reading until it does
while not quote[-1] == '"':
index += 1
quote += "\n" + lines[index].strip()
quotes[author].append(quote.strip('"'))
except ValueError:
pass
index += 1
for key, value in quotes.items():
print(f"{key}: {value}")
输出类似于
person 1: ['quotes', 'quotes 3'] person 2: ['quotes2', 'quotes 4']
您可以修改为写入文件而不是控制台。