2017-08-09 70 views
1

一個文本文件,在我的項目意見,我想提取從一個文本文件中的待辦事項清單。這是我迄今取得的進展。打印TODO:從Python中

這是todolist.txt文本文件的內容

#TODO:example4 
def printName(): 
    name=input("Enter your name: ") 
    print("Hello " + name) 
TODO:example3 
def printNumbers(): 
    for i in range (0,10):#TODO:example2 
     print(i) 


printName() 
printNumbers() 
#TODO: example1 

,這裏是與TODO提取行我的Python代碼:

file=open("todolist.txt","r") 

word="TODO:" 

for line in file: 
    if word in line: 
     print(line) 

當我運行這個程序的結果是:

#TODO:example4 

TODO:example3 

    for i in range (0,10):#TODO:example2 

#TODO: example1 


Process finished with exit code 0 

所以我的問題是在這裏我想提取和打印TODO線但你可以從上面看到,爲#TODO:例題我的程序印在spesific線前面的代碼了。

我想要做的是basicly只是打印TODO註釋。

+0

找到#字符的索引並打印從這一點就行了。 用'line [index:]'其中index指向#字符。你可以找到它的查找方法,例如 – Ivan

回答

2

您可以通過'TODO'分割線,然後得到最後一個項目。

word="TODO:" 
with open("todolist.txt") as file:  
    for line in file: 
     if word in line: 
      print("#TODO:" + line.split(word)[-1]) 
+0

謝謝你幫助這一個。我是Python的初學者。你能擴展'line.split(Word)[ - 1]'部分嗎? -1的值是什麼? –

+0

@onurcevik [-1]用法,獲取可以被索引的對象的最後一項。像[0]是第一個項目,[1]是第二個項目等等。由於split返回一個列表,它獲取最後一個項目,在這種情況下,它是「TODO」之後的部分。 – Lafexlos

0

您可以使用正則表達式:

  • 開始與任意數量的空格(0個或更多)
  • 包含#TODO:

    import re 
    
    with open("todolist.txt") as f: 
        file_content = f.read() 
    
    print(re.findall(r'^\s*#TODO:.+$', file_content, re.MULTILINE)) 
    
    # ['#TODO:example4', '#TODO: example1'] 
    

    '^\s*#TODO:.+$'將每行匹配其次是什麼(1個或多個)

  • 包含閒來無事