홈>
Filesystem Type 1K-blocks Used Available Use% Mounted on
/dev/sda ext4 245671 47009 181459 21% /initlo
/dev/loop7 squashfs 39552 39552 0 100% /
none tmpfs 65536 1064 64472 2% /tmp
none aufs 65536 1064 64472 2% /dev
none tmpfs 510184 24 510160 0% /dev/shm
none aufs 65536 1064 64472 2% /etc
none aufs 65536 1064 64472 2% /var
none aufs 65536 1064 64472 2% /www
none aufs 65536 1064 64472 2% /mcl
none aufs 65536 1064 64472 2% /eds
사전을 생성하고 싶을 때 (키를 테이블의 헤더로 사용하고 값은 각 열에 따라야 함) 이 사전을 만드는 데 도움을주십시오. 표 그림을 보려면 링크를 클릭하십시오.
-
답변 # 1
-
답변 # 2
@Rishikesh Jha (감사)에서 영감을 얻어 제안 된 답변은 다음과 같습니다 (팬더와 같은 고급 라이브러리를 사용하지 않고) :
import re INPUT = """Filesystem Type 1K-blocks Used Available Use% Mounted on /dev/sda ext4 245671 47009 181459 21% /initlo /dev/loop7 squashfs 39552 39552 0 100% / none tmpfs 65536 1064 64472 2% /tmp none aufs 65536 1064 64472 2% /dev none tmpfs 510184 24 510160 0% /dev/shm none aufs 65536 1064 64472 2% /etc none aufs 65536 1064 64472 2% /var none aufs 65536 1064 64472 2% /www none aufs 65536 1064 64472 2% /mcl none aufs 65536 1064 64472 2% /eds """ def split_spaces(s): "Split a string into a list, using spaces/tabs as separators" return re.split('\s+', s.strip()) def make_dict(input): "Convert a string containing a table into a list of dictionaries" input_list = input.splitlines() output_list = [] # get the keys: keys = split_spaces(input_list[0]) # get the list of dictionaries: for line in input_list[1:]: values = split_spaces(line) output_list.append({key: value for key,value in zip(keys, values)} ) return output_list print("Table: ", make_dict(INPUT)) row1 = d[0] print("First row:", row1) print("The type of first row is:", row1['Type'])
결과는 다음과 같습니다.
Table: [{'Filesystem': 'Mounted', 'Type': 'on'}, {'Filesystem': '/dev/sda', 'Type': 'ext4', '1K-blocks': '245671', 'Used': '47009', 'Available': '181459', 'Use%': '21%'}, {'Filesystem': '/dev/loop7', 'Type': 'squashfs', '1K-blocks': '39552', 'Used': '39552', 'Available': '0', 'Use%': '100%'}, {'Filesystem': 'none', 'Type': 'tmpfs', '1K-blocks': '65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%'}, {'Filesystem': 'none', 'Type': 'aufs', '1K-blocks': '65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%'}, {'Filesystem': 'none', 'Type': 'tmpfs', '1K-blocks': '510184', 'Used': '24', 'Available': '510160', 'Use%': '0%'}, {'Filesystem': 'none', 'Type': 'aufs', '1K-blocks': '65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%'}, {'Filesystem': 'none', 'Type': 'aufs', '1K-blocks': '65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%'}, {'Filesystem': 'none', 'Type': 'aufs', '1K-blocks': '65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%'}, {'Filesystem': 'none', 'Type': 'aufs', '1K-blocks': '65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%'}, {'Filesystem': 'none', 'Type': 'aufs', '1K-blocks': '65536', 'Used': '1064', 'Available': '64472', 'Use%': '2%'}] First row: {'Filesystem': '/dev/sda', 'Type': 'ext4', '1K-blocks': 245671, 'Used': 47009, 'Available': 181459, 'Use%': '21%', 'Mounted': '/initlo', 'on': nan} The type of first row is: ext4
와이즈 비즈 공백이나 탭이 여러 개 있거나 두 가지가 혼합되어 있으면 어쨌든 작동하기에 충분히 강력합니다.
split_spaces
의 정의를 참조하십시오 정규식으로;상징\s
"하나 이상"을 의미합니다. -
답변 # 3
내 이해에서 "파이썬 사전에서 위의 출력을 포함하는 문자열을 어떻게 변환 할 수 있습니까?"라는 질문이 있습니다.
하나의 가능한 해결책은 팬더가 당신을 위해 발판을 만들도록하는 것입니다 (파일에 테이블이 있다고 가정) :
+
import pandas input_file = "input.txt" t = pandas.read_csv(input_file, sep='\s+') print("Here is the dictionary of dictionaries:") d = t.to_dict(orient='index') print("List of keys:", d.keys()) row1 = d[0] print("First row:", row1) print("The type of first row is:", row1['Type'])
)에 있습니다. : 하나 이상의 공백/탭)이것은 출력입니다 :
\s+
Here is the dictionary of dictionaries: List of keys: dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) First row: {'Filesystem': '/dev/sda', 'Type': 'ext4', '1K-blocks': 245671, 'Used': 47009, 'Available': 181459, 'Use%': '21%', 'Mounted': '/initlo', 'on': nan} The type of first row is: ext4
관련 자료
- PowerShell 출력을 Python으로 변환하고 변수에 저장
- python - 사용자 입력이 $XXXX 형식인지 확인하는 방법은 무엇입니까? $XX 형식 일 수도 있지만 프로그램은이를 소수점 이하 2 자리 부동으로 변환합니다
- package managers - lua 테이블을 C ++ 배열 또는 벡터로 변환하는 간단한 방법이 있습니까?
- azure - Kusto에서 JSON을 키 값 테이블로 변환하는 방법
- c - 내 코드가 예상대로 트리플을 출력하지 않습니다 무슨 문제일까요?
- python - 문자열을 부동 소수점으로 변환 할 수 없습니다 - '1000000 %'
- python - 문자열을 부동 소수점으로 변환 할 수 없음 - '2648142'(panda)
- excel - 파워 쿼리, 새로 고치는 동안 출력 테이블 크기를 동일하게 유지
- r - 분할 표 출력에서 행 및 레이블 교체
- python - 패키지 공간 - nonetype 출력을 사전으로 변환
- python - 병합 테이블 출력에 중복 레코드가 포함되어 있습니다
- python - 아래 출력을 데이터 프레임으로 변환해야 함
- apache flink - pyflink - scala udf :table api에서 scala map을 변환하는 방법은 무엇입니까?
- 줄 열이있는 표 형식으로 텍스트 파일의 출력을 인쇄하는 방법
- sql - 긴 텍스트 열이있는 JSON 배열로 테이블 변환
- c++ - 오류 - 'tab'을 'vector >'에서 'vector '로 변환 할 수 없습니다
- python - valueerror - 문자열을 float로 변환 할 수 없습니다 : 'erght'
- python - 여러 구분 기호가 포함 된 텍스트 파일을 CSV로 변환
- sql - TIMESTAMP를 VARCHAR로 변환하고 Redshift의 다른 테이블에 저장하는 방법은 무엇입니까?
- mysql - Python에서 SQL 출력을 문자열로 변환
관련 질문
- 문자가 20보다 크면 무엇을 사용할지 파이썬 코드를 작성했습니다 사용자로부터 다시 입력을 받아 계산을 수행합니다
- python - readline () 메서드에서 오류가 발생합니다 attributeerror - 'tuple'개체에 'readline'속성이 없습니다
- python - 프레임 드롭률 계산 문제
- python - python2 스크립트를 python3으로 포팅 - 구조체 라이브러리
- 파이썬에서 바이너리 파일을 읽고 그것을 정수 배열로 변환하는 방법은 무엇입니까?
- Linux에서 python 명령을 찾을 수 없음
- python - pip install uvloop로 인해 권한 거부 오류가 발생합니다
- 목록 문제의 Python 목록
- 파이썬에서 문자열 형식을 사용하여 원하는 출력을 얻을 수 없습니다
출력은 탭으로 구분 된 문자열/탭으로 구분 된 문자열 목록 인 것 같습니다. 전체 문자열을 문자열 목록으로 변경합니다
출력 :