2017-08-09 112 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个或多个)

  • 包含闲来无事