[英]Printing TODO: comments from a text file in Python
In my Project I want to extract the to do list from a text file. 在我的项目中,我想从文本文件中提取待办事项列表。 Here is my progress so far. 到目前为止,这是我的进度。
This is the content of todolist.txt
text file 这是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
and here is my Python code for extracting lines with TODO : 这是我的Python代码,用于使用TODO提取行:
file=open("todolist.txt","r")
word="TODO:"
for line in file:
if word in line:
print(line)
And when I run this program the result is: 当我运行该程序时,结果是:
#TODO:example4
TODO:example3
for i in range (0,10):#TODO:example2
#TODO: example1
Process finished with exit code 0
So my problem is here I want to extract and print TODO lines only but as you can see from above, for #TODO:example2 my program printed the previous code on that spesific line too. 所以我的问题是在这里我想提取和打印TODO线仅但你可以从上面看到,对于#TODO:例题我的程序印在spesific线前面的代码了。
What I want to do is basicly just printing TODO comments. 我要做的基本上只是打印TODO注释。
You can split the line by 'TODO'
then get the last item. 您可以按'TODO'
分隔行,然后获取最后一项。
word="TODO:"
with open("todolist.txt") as file:
for line in file:
if word in line:
print("#TODO:" + line.split(word)[-1])
You can use a regex: 您可以使用正则表达式:
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:.+$'
will match every line that: '^\\s*#TODO:.+$'
将匹配每行:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.