2014-06-30 49 views
0

假設我有一個正在操作的文本文件。像這樣的東西(希望這是不是太不可讀):在異常處理程序Python:獲取字符串索引的行號和列號?

data_raw = open('my_data_file.dat').read() 
matches = re.findall(my_regex, data_raw, re.MULTILINE) 
for match in matches: 
    try: 
     parse(data_raw, from_=match.start(), to=match.end()) 
    except Exception: 
     print("Error parsing data starting on line {}".format(what_do_i_put_here)) 
     raise 

通知書有一定的變量命名爲what_do_i_put_here。我的問題是:如何分配該名稱以便我的腳本將打印行號碼,其中包含我正在嘗試使用的「壞區域」的開始?我不介意重讀這個文件,我只是不知道該怎麼辦...

+0

您的正則表達式是否會消耗新行?如果不行,你可以逐行找到所有行,然後很容易得到行號。 – dustyrockpyle

+0

是的,它消耗了多行(這就是爲什麼我使用're.MULTILINE') –

+0

不re.findall返回字符串列表?:https://docs.python.org/2/library/re.html 。字符串沒有開始或結束方法。 –

回答

0

我寫了這個。這是未經檢驗的和低效的,但它確實有助於我的異常消息是略知一二:

def coords_of_str_index(string, index): 
    """Get (line_number, col) of `index` in `string`.""" 
    lines = string.splitlines(True) 
    curr_pos = 0 
    for linenum, line in enumerate(lines): 
     if curr_pos + len(line) > index: 
      return linenum + 1, index-curr_pos 
     curr_pos += len(line) 

我還沒有測試,看看如果列數是隱約準確。我沒有遵守YAGNI

+1

我建議使用's'來避免陰影標準庫'字符串'模塊。 –

相關問題