【问题标题】:Printing TODO: comments from a text file in Python打印 TODO:Python 文本文件中的注释
【发布时间】:2017-08-09 13:31:57
【问题描述】:

在我的项目中,我想从文本文件中提取待办事项列表。这是我到目前为止的进展。

这是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 行 only 但正如您从上面看到的那样,对于 #TODO:example2 我的程序打印了前面的代码也在那条特定的线上。

我想做的基本上就是打印 TODO cmets。

【问题讨论】:

  • 找到 # 字符的索引并打印从该点开始的行。 line[index:] 其中 index 指向 # 字符。例如,您可以使用 find 方法找到它

标签: python text todo


【解决方案1】:

您可以通过'TODO' 拆分行,然后获取最后一项。

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

【讨论】:

  • 谢谢这个帮助。我是 Python 的初学者。你能解释一下line.split(Word)[-1] 部分吗? -1 值有什么作用?
  • @onurcevik [-1] 用法,获取可以索引的对象的最后一项。就像 [0] 是第一项,[1] 是第二项等。由于 split 返回一个列表,所以它获取最后一项,在这种情况下,它是“TODO”之后的部分。
【解决方案2】:

您可以使用正则表达式:

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:.+$' 将匹配以下每一行:

  • 以任意数量的空格开头(0 个或更多)
  • 包含 #TODO 后跟任何内容(1 个或多个)
  • 不包含任何其他内容

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-02
    • 2014-04-29
    • 2023-03-07
    • 2014-08-28
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多