我有两个数组,infile
和outfile
:
infile = ['Apple', 'Orange', 'Banana']
outfile = ['Applefile', 'Orangefile', 'Bananafile']
我在readin.txt
中搜索infile
数组中的每个元素,对于包含所述元素的任何一行,我会做一些事情。这就是readin.txt
的样子:
Apple = 13
Celery = 2
Orange = 5
Banana =
Grape = 4
outfile
数组包含我要创建的文件的名称;每个文件对应于infile
中的一个元素。infile
中的第一个元素对应于outfile
中的第一个元素(文件名),依此类推。你知道吗
我遇到的问题是这段代码:
for line in open("readin.txt", "r"):
for i in infile:
if i in line:
sp = line.split('=')
sp1 = str(sp[1])
def parseline(l):
return sp1.strip() if len(sp) > 1 and sp[1].strip() != '' else None
for s in outfile:
out = parseline(line)
outw = open(s, "w")
outw.write(str(out))
outw.close()
在代码的第一部分,我想在readin.txt
中搜索infile
(即Apple
、Orange
和Banana
)中的任何一个单词。然后,我希望代码选择出该单词出现的整行。我知道readin.txt
中的任何这样的行都将包含一个等号,因此我希望代码围绕等号拆分该行,并只生成等号后面的行。你知道吗
虽然代码的最后一部分确实为outfile
中的每个元素创建了单独的文件,但实际的输出总是对应于infile
的最后一个元素。就好像循环中的每个后续步骤都覆盖了前面的步骤。我觉得我需要查看i
的第line
个元素,但我不知道如何在Python中这样做。任何帮助都会很好。你知道吗
为清晰起见进行编辑,并希望重新打开问题:
实际上,下面的代码似乎正是我想要的:
for line in open("parameters.txt", "r"):
for i in infile:
if i in line:
sp = line.split('=')
sp1 = str(sp[1]).strip() if len(sp) > 1 and sp[1].strip() != '' else None
print sp1
在命令行上,我得到:
13
5
None
所以这告诉我,代码的第一部分基本上是在做我希望它做的事情(虽然可能不是以最有效的方式,所以任何其他的建议都会很感激)。你知道吗
此时,我希望打印出来的所有信息都基于outfile数组写入到各个文件中。也就是说13
应该被输入一个名为Applefile
的文件,None
应该被写入一个名为Bananafile
的文件,等等。这就是我遇到的问题。我知道'outfile'应该以类似的方式编制索引,以便outfile的第一个元素对应于infile的第一个元素,但我的尝试到目前为止还没有成功。你知道吗
这是我最近的一次尝试:
for line in open("parameters.txt", "r"):
for i in infile:
if i in line:
def parseline(l):
sp = l.split('=')
sp1 = str(sp[1]).strip() if len(sp) > 1 and sp[1].strip() != '' else None
if sp1:
out = parseline(line)
outw = open(outfile[i], "w")
outw.write(line)
outw.close()
因为某种原因,在代码中提前定义parseline
会否定代码的整个开头部分。你知道吗
我不是在寻找答案。我想了解发生了什么,并能够找出如何解决它。你知道吗
我将把它分解为两个步骤:
您当前的代码没有什么意义:
在两个循环中使用相同的循环变量名是个坏主意,您只能看到内部值:
如果您发现某个函数“需要”在某个特定位置定义,则表明您正依赖作用域来访问变量。为所需的参数定义特定的参数和返回值要好得多;这使开发和测试更加容易。你知道吗
因为对于infile的每一个元素,您都在outfile的每一个元素上循环并写入最新的一行,所以最终所有文件都包含最后一行是有意义的。由于您的infile/outfile行对应,您可以使用主infile循环中的i索引从outfile获取您想要的标签。。比如:
相关问题 更多 >
编程相关推荐