我正在对一个文本文件执行文本处理,并尝试迭代到for循环中。你知道吗
fields = [1, 2, 3, 4, 5]
i = 0
with open('file path', 'r') as f:
for line in f:
# while i is smaller than the number of fields (=5)
while i <= len(fields)-1:
currentfield = fields[i]
# if the first character of the line matches currentfield
# (that being a number)
if line[0] == currentfield:
print(line[4:]) # print the value in the "third column"
i += 1
文本文件“f”有如下内容(虚线之间的数字表示年份,每年都有自己的“条目”):
-------------2000--------------
1 17824
2 20131125192004.9
3 690714s1969 dcu 000 0 eng
4 a 75601809
4 a DLC
4 b eng
4 c DLC
5 a WA 750
-------------2001--------------
1 3224
2 20w125192004.9
3 690714s1969 dcu 000 0 eng
5 a WA 120
-------------2002--------------
1 6563453
2 2013341524626245.9
3 484914s1969 dcu 000 0 eng
4 a 75601809
4 a eng
4 c DLC
5 a WA 345
文本文件中实际上没有列,但字段编号(即1、2、3、4、5)和后面的值(即17824)之间的空格有两个制表符。我只是不知道怎么打电话给17824。你知道吗
我要做的是迭代每个条目/年份的所有字段,但输出仅给出第一个字段的值1。因此,我得到如下输出:
17824
3224
6563453
它只迭代第一个字段,而不是迭代所有字段。如何修复代码,以便将输出创建为类似于表的形式,并在其中迭代字段2、3、4和5?像这样:
17824 20131125192004.9 690714s1969 dcu 000 0 eng ...and so on
3224 20w125192004.9 690714s1969 dcu 000 0 eng ...and so on
6563453 2013341524626245.9 484914s1969 dcu 000 0 eng ...and so on
编辑:我知道我不是很清楚,所以我添加了一些部分。你知道吗
这将帮助您:
这给了我:
顺便说一下,将
line[:4]
更改为line[:8]
将得到上面粘贴的数据的第三列。你知道吗然后可以使用regex删除第三列数据后空格后面的任何内容。你知道吗
为更改的Q编辑
在这里,我将每一行连接起来,并用
l = [el for el in ''.join(line) if el != '']
删除列中的所有空格。然后可以通过直接引用列来索引该列,例如对于第4列:l[4]
相关问题 更多 >
编程相关推荐