我有一个函数,它循环遍历一个如下所示的文件:
"#" 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")我想我的麻烦是在找到以"#“开头的一行之后,我如何解析/搜索它呢?并保存它的内容,如果它包含需要的词。
发布于 2019-01-30 21:03:48
如果#注释中包含如上所述的str Column.4:,您可以这样解析它。
with open(filepath) as f:
for line in f:
if line.startswith('#'):
# Here you proceed comment lines
if 'Column.4' in line:
first, remainder = line.split('Column.4: ')
# Remainder contains everything after '# Column.4: '
# So if you want to get first word ->
word = remainder.split()[0]
else:
# Here you can proceed lines that are not comments
pass备注
另外,使用for line in f:语句代替f.readlines() (正如其他答案中提到的那样)也是一个很好的实践,因为这样您不会将所有行加载到内存中,而是一个接一个地处理它们。
发布于 2019-01-30 20:55:40
首先,您应该将文件读入列表中,然后进行如下操作:
file = 'test.txt' #<- call file whatever you want
with open(file, "r") as f:
txt = f.readlines()
for line in txt:
if line.startswith ('"#"'):
word = line.split(" Column.4: ")
try:
print(word[1])
except IndexError:
print(word)
else:
print("n")输出:
>>> ['"#" XDI/1.0 XDAC/1.4 Athena/0.9.25\n']
>>> pre_edge使用了try和except,因为第一行也是以"#“开头的,我们不能用当前的逻辑来分割它。
另外,作为附带说明,在这个问题中,文件的行以"#“开头,引号为”#“,因此startswith()函数被修改为这样。
发布于 2019-01-30 21:07:19
with open('stuff.txt', 'r+') as f:
data = f.readlines()
for line in data:
words = line.split()
if words and ('#' in words[0]) and ("Column.4:" in words):
print(words[-1])
# pre_edgehttps://stackoverflow.com/questions/54449176
复制相似问题