python - 使用 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
解决方案
我不确定分割线本身是否有帮助,因为每条线只有一条数据;您需要跨多行收集数据。试一试:
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)
推荐阅读
- java - 如何将动态加载的单选按钮放入一个组中?
- php - Laravel-在模型实例上设置原始属性值(绕过强制转换逻辑)
- python - 撇号导致字符串比较出现问题?
- python - 如何检测与敌人相撞的导弹?
- c# - 如何使用 Microsoft Graph SDK 获取 AD 用户组列表以及 AD 用户
- email - 电子邮件服务器是否具有标准文件夹命名或 ID?
- reactjs - React Material-ui自动完成:清除搜索字段时出现“TypeError:无法读取null的属性'id'”
- r - zip() 函数在 R Studio 中不起作用:如何使用密码创建压缩文件 .zip?
- vue.js - Vue.js - 翻译文件以获得更好的性能
- java - 使用 SceneBuilder 的 JavaFX 错误