문제 설명
분할 방법을 사용하여 텍스트 파일에서 범주를 열로 분리 (Using the split method to separate categories into columns from a text file)
그래서 카테고리에 따라 줄을 열로 구분하여 파이썬 프로그래머에서 파일을 읽는 데 문제가 있습니다. 예를 들어, name
행은 그 아래에 다른 이름이고, Occupation
행은 그 아래에 서로 다른 직업 제목이 있고 location<행은 /code> 아래에 다른 도시가 있습니다. 이 모든 행이 있는 파일을 열고 이 세 가지 범주에 따라 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
참조 솔루션
방법 1:
I'm not sure if splitting lines is in itself that helpful since each line only has one piece of data; you need to collect data across multiple lines. Give this a whirl:
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)
참조 문서