我有一个函数,它循环遍历一个如下所示的文件:
"#" XDI/1.0 XDAC/1.4 Athena/0.9.25
"#" Column.4: pre_edge
Content
也就是说在“#”之后有一个注释。我的功能是阅读每一行,如果它以一个特定的单词开头,请选择“:”后面的内容
例如,如果我有这两条线。我想通读它们,如果行以“#”开头并包含单词“Column.4”,则应该存储单词“pre#edge”。你知道吗
我目前的方法的一个例子如下:
with open(file, "r") as f:
for line in f:
if line.startswith ('#'):
word = line.split(" Column.4:")[1]
else:
print("n")
我想我的问题是在找到以“#”开头的行之后,如何解析/搜索它?如果包含所需单词,则保存其内容。你知道吗
您应该先将文件读入一个列表,然后再进行处理:
输出:
使用了try-and-except-catch,因为第一行也以“#”开头,我们不能用当前的逻辑拆分它。你知道吗
另外,作为旁注,在这个问题中,您有一个以“#”开头并带有引号的文件,因此
startswith()
函数被更改为这样。你知道吗如果
#
注释包含上面提到的strColumn.4:
,您可以这样解析它。你知道吗注
另外,使用
for line in f:
语句而不是f.readlines()
(如其他答案中所述)也是一种很好的做法,因为这样您就不会将所有行加载到内存中,而是逐个执行它们。你知道吗相关问题 更多 >
编程相关推荐