首页 > 解决方案 > 使用 split 方法将文本文件中的类别分成列

问题描述

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

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

标签: pythontextsplitmultiple-columns

解决方案


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

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)

推荐阅读