분할 방법을 사용하여 텍스트 파일에서 범주를 열로 분리 (Using the split method to separate categories into columns from a text file)


문제 설명

분할 방법을 사용하여 텍스트 파일에서 범주를 열로 분리 (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)

(by Ana BairdSamwise)

참조 문서

  1. Using the split method to separate categories into columns from a text file (CC BY‑SA 2.5/3.0/4.0)

#split #Python #multiple-columns #text






관련 질문

오류: 이 범위에서 '분할'이 선언되지 않았습니다. (error: ‘split’ was not declared in this scope)

화살표 문자가 포함된 문자열 분할 (Split a string containing arrow characters)

문자 수로 문자열의 특정 부분 가져오기 (Take specific part of a string by character count)

VBScript: 새로운 분할 항목이 있는 리조트 문자열 및 그룹 (VBScript: Resort String and group with new Split Item)

python 태그에서 단어와 숫자 나누기 (Split words and numbers from tags python)

구두점을 문자열 끝에서 시작 부분으로 이동하려면 어떻게 해야 합니까? (How can I move the punctuation from the end of a string to the beginning?)

쉼표로 문자열을 분할하지만 대괄호 또는 따옴표로 묶인 쉼표는 무시하십시오. (Split string by comma but ignore commas in brackets or in quotes)

숫자를 나누고 점 뒤에 하나의 숫자를 유지하십시오. (Split the number and keep one number after the dot)

Oracle에서 쉼표로 구분된 문자열의 최대 개수를 얻는 방법은 무엇입니까? (How to get maximum COUNT of comma separated string in Oracle?)

분할 방법을 사용하여 텍스트 파일에서 범주를 열로 분리 (Using the split method to separate categories into columns from a text file)

Powershell에서 문자열 분할 및 추가 (Splitting and Adding String in Powershell)

원래 문자열 포인터를 수정하지 않는 strtok_r() 및 strsep()에 대한 C-문자열 대안? (C-string alternatives to strtok_r() and strsep() that don't modify the original string pointer?)







코멘트