我是 python 的新手,我写的这段代码有问题:
#! /usr/bin/env python
OutFileName = "k_values.txt"
OutFile = open(OutFileName, 'w')
with open("structure_working.txt") as infile:
for Line in open("structure_working.txt"):
Line = Line.strip('\n')
ElementList = Line.split('\t')
k1 = ElementList[2]
k2 = ElementList[3]
k3 = ElementList[4]
k4 = ElementList[5]
k = 1
if k2 > k:
k = 2
if k3 > k2:
k = 3
if k4 > k3:
k = 4
name = ElementList[1]
OutputString = "%s\t%s" % (name, k)
print OutputString
OutFile.write(OutputString + "\n")
OutFile.close()
我的输入文件是制表符分隔文件。问题是我的 for 循环只在标题行上运行一次,而不会继续进入文件正文。这是我的文本文件的示例:
num indiv 1 2 3 4 k
1 JB1972 0.642 0.141 0.091 0.127
2 JB1973 0.754 0.113 0.079 0.055
3 JB1974 0.069 0.422 0.418 0.091
4 JB1976 0.175 0.339 0.249 0.237
5 JB1977 0.149 0.365 0.383 0.103
6 JB1978 0.421 0.184 0.146 0.249
7 JB1979 0.264 0.246 0.395 0.095
8 JB1980 0.074 0.511 0.287 0.128
9 JB1981 0.083 0.162 0.275 0.48
10 JB1982 0.059 0.145 0.73 0.067
我找到的“for 循环只运行一次”问题的答案对我的具体问题没有帮助。代码在标题行上运行的事实让我认为问题出在 for 循环上。有任何想法吗?
请您参考如下方法:
您应该将代码更改为类似于以下(未经测试)的示例:
import csv
# use with statement for file handling
# note that nesting is also possible and kind of convenient
with open(outfname, 'w+') as outf, open(infname) as inf:
# use csv.reader and csv.writer to specify csv file format
# also have a look at csv.DictReader (I like it much better...)
reader = csv.reader(inf, delimiter='\t')
writer = csv.writer(outf, delimiter='\t')
# skip the header line (not necessary when csv.DictReader is used)
reader.next()
# iterate input lines
for line in reader:
# split line without having to deal with the proper formatting
name = line[1]
# somehow compute k value (probably I haven't got it right)
k = max(enumerate(map(float, line[2:6])), 1), key=lambda x:x[1])[0]
# write row without having to deal with proper formatting
writer.writerow([name, k])
尽可能使用 with 语句来处理文件。它们提供易于使用的包装器以实现故障安全自动关闭和简洁的语法(在我看来)。请注意,在一个 with block 中嵌套多个文件也是可能且方便的。
您正在读取一个 csv 文件(字符分隔值)。 Python 在其标准库中为此提供了一个模块(您应该尽可能使用标准库)。还要考虑像 pandas 这样的框架,它们还提供方便处理 csv(或 excel)文件的功能。
当您正确处理了读取和写入 csv 文件的问题后,您终于可以重新审视计算 k 值的逻辑。正如您在我的示例中所看到的,在比较它们之前,我已将输入文件中的字符串转换为数字。此外,我假设您想获得最大值的列号,所以我尝试实现它。当您尝试实现类似的东西时,请再次查看标准库提供的功能(除了 if 语句)。这将大大改善您的生活(和代码质量)。作为开始,我在下面放置了一些指向文档的链接。
供引用:
- https://www.python.org/dev/peps/pep-0343/
- https://docs.python.org/2/library/csv.html
- http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
- https://docs.python.org/2/library/functions.html#map
- https://docs.python.org/2/library/functions.html#enumerate
- https://docs.python.org/2/library/functions.html#max
- Explain Python's slice notation
