2016-08-13 59 views
0

我有一個腳本解析真實在此文件中的第一個大寫的話:解析成功直到IndexError?

IMPORT fs 

IF fs.exists("fs.pyra") THEN 
    PRINT "fs.pyra Exists!" 
END 

腳本是這樣的:

file = open(sys.argv[1], "r") 
file = file.read().split("\n") 

while '' in file: 
    findIt = file.index('') 
    file.pop(findIt) 

for line in file: 
    func = "" 
    index = 0 
    while line[index] == " ": 
     index = index + 1 
    while not line[index] == " " or "=" and line[index].isupper(): 
     func = func + line[index] 
     index = index + 1 
    print func 

所有使用的模塊已經導入。
我通過正在解析的路徑參數的文件,我得到這樣的輸出:

IMPORT 
IF 
PRINT 
Traceback (most recent call last): 
    File "src/source.py", line 20, in <module> 
    while not line[index] == " " or "=" and line[index].isupper(): 
IndexError: string index out of range 

這意味着它的成功解析,直到在列表中的最後一個參數,然後它不解析它在所有。我該如何解決?

+0

'而不用排隊[指數] ==「」或「=」'不是在做你認爲的事情 - 你可能是指'in('=')'而不是? –

+0

'file.read()。split(「\ n」)'...?爲什麼不'file.readlines()'? –

+0

@ cricket_007'file.readlines()'在其中留下換行符。 – baranskistad

回答

0

您不需要增加空間上的索引 - line.strip()將刪除前導和尾隨空格。

您可以在split()空格處獲得單詞。

然後你可以遍歷這些字符串,並使用isupper()檢查整個單詞,而不是單個字符


另外,運行通過模式匹配整個文件[A-Z]+


不管怎麼說,你的錯誤...

while not line[index] == " " or "=" 

or "="始終爲真,因此您的索引超出範圍

0

如果您要處理的文件與Python內置的標記器兼容,則可以使用該標記,以便它可以處理引號內的內容,然後採取非常第一名令牌它在首都發現從每一行中,例如:

import sys 
from itertools import groupby 
from tokenize import generate_tokens, NAME 

with open(sys.argv[1]) as fin: 
    # Tokenize and group by each line 
    grouped = groupby(tokenize.generate_tokens(fin.readline), lambda L: L[4]) 
    # Go over the lines 
    for k, g in grouped: 
     try: 
      # Get the first capitalised name 
      print next(t[1] for t in g if t[0] == NAME and t[1].isupper()) 
     except StopIteration: 
      # Couldn't find one - so no panic - move on 
      pass 

這給你:

IMPORT 
IF 
PRINT 
END