【问题标题】:Using the split method to separate categories into columns from a text file使用 split 方法将文本文件中的类别分成列
【发布时间】:2020-04-15 06:36:50
【问题描述】:

所以我无法通过根据类别将行分成列来尝试在 python 程序员中读取文件。比如name下面是不同的名字,然后Occupation下面有不同的职业名称,location下面有不同的城市。我需要打开包含所有这些行的文件,并根据这三个类别将它们分成 3 列。我尝试了splitrsplitsplittinglines 方法,但它们都不起作用。我究竟做错了什么?例如,这就是我正在做的:

fhand = open('names.txt')
for line in fhand:
line = line.rsplit()
print(line)"

文件如下所示:

Name:
Pat M.
Jorge M.
Johnny N.
Occupation:
Professor
Web Developer
Computer Scientist
Location:
Delta College
Pleasanton
Lawrence Livermore Lab

【问题讨论】:

  • 在任何人能够帮助您之前分享一些示例文本
  • 文本文件不适合此类数据。您应该将其保存为 CSV 或 Excel 文件,然后使用 pandas 等库对其进行处理。
  • Arashsyh:我的教授给了我和其他同学这个作业的文本文件,因此我的问题在这里。我将以这个文件为例回答我自己的问题。

标签: python text split multiple-columns


【解决方案1】:

我不确定分割线本身是否有用,因为每条线只有一条数据;您需要跨多行收集数据。试一试:

from typing import Dict, List, Optional
from collections import defaultdict

column: Optional[str] = None
columns: Dict[str, List[str]] = defaultdict(list)
with open('names.txt') as fhand:
    for line in fhand:
        line = line.strip()

        # Is this the start of a new column?
        if line[-1] == ":":
            column = line[:-1]
        # If not, append this to the current column.
        elif column is not None:
            columns[column].append(line)
print(columns)

【讨论】:

  • 谢谢,但结果并没有达到我的预期;取而代之的是,每个单词都紧挨着出现,除了对于每个类别,每个对应的行都在括号之间。我知道这很难,但我不知道我的教授如何让他的学生使用文本文件而不是更简单的应用程序来完成这项作业。无论如何,感谢您的帮助。
  • 我只是向您展示了如何将文件读入数据结构,该数据结构以易于访问的格式包含您需要的所有信息。以您想要的方式输出它取决于您(这是最简单的部分,但只有您知道它必须如何完成,因为它不是问题的一部分)。祝你好运! :)
最近更新 更多