2017-12-14 16 views
2

혼란스러운 제목에 사과드립니다. 파이썬에 아주 새로운 해요 여기에 내가 달성하기 위해 노력하고있어입니다 :파이썬에서 파일을 구문 분석하고 값을 저장하는 동안 여러 줄 건너 뛰기

file.txt를 :

을 나는이 같은 데이터 (및 기타 물건)을 가진 파일 file.txt 파일을 구문 분석하고 있습니다

... 
a = (
1 
2 
3) 
... 

는 I 2 개 부분이 유형의 데이터를 저장해야

명 = "A"

값 = { "(", "1", "2", "3)" }
^ eac h 줄은 목록의 요소입니다.

아래 코드 조각과 같이 파일을 한 줄씩 구문 분석 중이므로 변경할 수 없습니다. 데이터를 저장하는 방법을 잘 모르겠습니다. 몇 줄을 살펴보고 값을 저장 한 다음 두 번 처리하지 않도록 건너 뜁니다. 나는 루프 "는 ="도움을

with open(file.txt) as fp: 
    for line in fp: 
     ... 

덕분에 첫 번째 줄에있을 때이 개 변수의 이름과 값이 채워합니다.

답변

0

따라서 파일을 라인별로 분석합니다. 행에서 등호 "="을 찾을 때마다 "="앞의 char은 원하는 이름 값입니다. 다음 줄은 목록의 첫 번째 요소, 두 번째 요소 뒤에 오는 줄 등 ... 줄에 char이있는 경우) ")"은 목록의 마지막 값임을 나타냅니다. See the Python string.find method for this. 개념을 이해하고 코딩이 어렵지 않아야합니다.

0
[u'a'] 
['(', '1', '2', '3', ')'] 

이게 필요한가요?

import nltk 

name = [] 
value = [] 
with open("file.txt") as fp: 
    for line in fp: 
     words = line.split() 
     if ('(') in words: 
      name.append(words[0].decode('utf-8')) 
      value.append('(') 
     else: 
      for entry in words: 
       value.append(entry) 

print (name) 
print (value) 

fp.close() 
1

을 나는 사전을 사용하는 것이 좋습니다 :

그런 다음 코드 줄 따라 할 수있는 파일이 너무 크지 않으면

txt=open(r"file.txt","r").readlines() 
dictionary=dict() 
for i in range(len(txt)): 
    if "=" in txt[i]: 
     name,values=txt[i].split()[0],[txt[i].split()[-1]] 
     dictionary[name],i={"name":name},i+1 
     while True: 
      values.append(txt[i]) 
      if ")" in txt[i]: 
       break 
      i=i+1 
     values=[value.replace("\n","") for value in values] 
     dictionary[name].update({"values":values}) 
     i=i-1 
    i=i+1 

>>dictionary["a"] 
Out[40]: {'name': 'a', 'values': ['(', '1', '2', '3)']} 
>>dictionary["b"] 
Out[45]: {'name': 'b', 'values': ['(', '3', '4', '6)']} 
0

을 한 후 메모리에 전체 파일을 읽고 잠시 사용 루프는 세분화 된 제어 할 : 만 마지막 값이 ')'이 포함 된 경우, 그렇지

# python3 
with open("file.txt") as f: 
    lines = f.readlines() 
    index = 0 
    while True: 
     # do something here 

을, 이렇게 :

with open('file.txt') as f: 
    pairs = [] 
    for line in f: 
     values = [] 
     name, value = line.strip().split('=') 
     name = name.strip() 
     values.append(value.strip()) 
     while True: 
      line = next(f) 
      values.append(line.strip()) 
      if ')' in line: 
       break 
     pairs.append((name, values))