【问题标题】:Reading a text file inn python and creating two lists out of it在 python 中读取文本文件并从中创建两个列表
【发布时间】:2020-01-30 17:10:37
【问题描述】:

我有一个文本文件,其中包含对话内容

第 1 个人:“引用” 人 2:"quotes2" . . . 人 1:“引述 3” 人 2:“引用 4”

我想阅读第一个人的每个报价并将其放入列表中并再次将其另存为文本文件。还有另一个不同的列表来保存第 2 个人的报价和另一个不同的文件。我如何使用 python 来做到这一点,让每个引号可能是一行或多行?

【问题讨论】:

  • 嗨,我!请分享您的文件的一个小sn-p,并指定您希望您的2 个列表如何。我现在不明白你的问题。也分享你到目前为止尝试过的代码。
  • 您可以使用字典,其中键是人名,值是人名的列表。
  • @johny mopp:我如何检查报价是否属于应该是关键的那个人?鉴于报价可能是 line 或更多?
  • 抱歉回复晚了 - 出去吃午饭了。我已经输入了答案。

标签: python list text save


【解决方案1】:

您可以创建一个字典,其中键是作者的姓名,值是他们的引号列表。我会使用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}")

输出类似于

第 1 个人:['quotes', 'quotes 3'] 人 2: ['quotes2', 'quotes 4']

您可以修改为写入文件而不是控制台。

【讨论】:

  • 非常感谢您的评论。但是我得到值错误: ValueError: not enough values to unpack (expected 2, got 1) in this line author, quote = line.split(':')
  • 这意味着文件中至少有 1 行不是格式“author:quote”。我会更新答案
  • 是的,这是因为我提到引用可能是一行或多行。有没有办法解决这个问题?
猜你喜欢
  • 2020-10-17
  • 1970-01-01
  • 2020-03-28
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
相关资源
最近更新 更多