背景:
Table$Gene=Gene1
time n.risk n.event survival std.err lower 95% CI upper 95% CI
0 2872 208 0.928 0.00484 0.918 0.937
1 2664 304 0.822 0.00714 0.808 0.836
2 2360 104 0.786 0.00766 0.771 0.801
3 2256 48 0.769 0.00787 0.754 0.784
4 2208 40 0.755 0.00803 0.739 0.771
5 2256 48 0.769 0.00787 0.754 0.784
6 2208 40 0.755 0.00803 0.739 0.771
Table$Gene=Gene2
time n.risk n.event survival std.err lower 95% CI upper 95% CI
0 2872 208 0.938 0.00484 0.918 0.937
1 2664 304 0.822 0.00714 0.808 0.836
2 2360 104 0.786 0.00766 0.771 0.801
3 2256 48 0.769 0.00787 0.754 0.784
4 1000 40 0.744 0.00803 0.739 0.774
#There is a new line ("\n") here too, it just doesn't come out in the code.
我想要的似乎很简单。我想将上面的文件变成如下所示的输出:
Gene1 0.755
Gene2 0.744
即每个基因,以及每个部分的生存列中的最后一个数字。
我尝试了多种方法,使用正则表达式,将文件作为列表读入并说“.next()”。我尝试过的一个代码示例:
fileopen = open(sys.argv[1]).readlines() # Read in the file as a list.
for index,line in enumerate(fileopen): # Enumerate items in list
if "Table" in line: # Find the items with "Table" (This will have my gene name)
line2 = line.split("=")[1] # Parse line to get my gene name
if "\n" in fileopen[index+1]: # This is the problem section.
print fileopen[index]
else:
fileopen[index+1]
正如您在问题部分所看到的,我在这次尝试中试图说:
如果列表中的下一项是新行,则打印该项目,否则,下一行是当前行(然后我可以拆分行以提取特定数字我想)。
如果有人可以更正代码以便我可以看到我做错了什么,我将不胜感激。
最佳答案
有点矫枉过正,但不是手动为每个数据项编写解析器,而是使用像 pandas 这样的现有包来读取 csv 文件。只需要写一点代码来指定文件中的相关行。未优化的代码(读取文件两次):
import pandas as pd
def genetable(gene):
l = open('gene.txt').readlines()
l += "\n" # add newline to end of file in case last line is not newline
lines = len(l)
skiprows = -1
for (i, line) in enumerate(l):
if "Table$Gene=Gene"+str(gene) in line:
skiprows = i+1
if skiprows>=0 and line=="\n":
skipfooter = lines - i - 1
df = pd.read_csv('gene.txt', sep='\t', engine='python', skiprows=skiprows, skipfooter=skipfooter)
# assuming tab separated data given your inputs. change as needed
# assert df.columns.....
return df
return "Not Found"
这将读入一个包含该文件中所有相关数据的 DataFrame
然后可以做:
genetable(2).survival # series with all survival rates
genetable(2).survival.iloc[-1] last item in survival
这样做的好处是您可以访问所有项目,文件的任何格式错误都可能会被更好地拾取并防止使用不正确的值。如果是我自己的代码,我会在返回 pandas DataFrame 之前在列名上添加断言。想要尽早发现解析中的任何错误,以免它传播。
关于python 从文件中打印特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25202001/