gpt4 book ai didi

python - 集合中的索引中断

转载 作者:太空宇宙 更新时间:2023-11-04 10:28:03 26 4
gpt4 key购买 nike

我正在编写一个 python 脚本,它将如下文本文件作为输入:

0   A   (*) Begin
1 A
2 A
3 A
4 A
5 A (*) End
0 B (*) Begin
1 B
2 B
3 B
4 B
5 B
6 B (*) End
0 B (*) Begin
1 B
2 B (*) End
0 B (*) Begin
1 B
2 B
3 B
4 B (*) End

现在我想接收这样的输出:

0   A   (*) Begin [0]
1 A
2 A
3 A
4 A
5 A (*) End [0]
0 B (*) Begin [0]
1 B
2 B
3 B
4 B
5 B
6 B (*) End [0]
0 B (*) Begin [1]
1 B
2 B (*) End [1]
0 B (*) Begin [2]
1 B
2 B
3 B
4 B (*) End [2]

这将是翻译:

>>>A = [0,1,2,3,4,5]
>>>A
[0, 1, 2, 3, 4, 5]
>>>len(A)
6
>>>B = [(0,1,2,3,4,5,6), (0,1,2), (0,1,2,3,4)]
>>>B
[(0,1,2,3,4,5,6), (0,1,2), (0,1,2,3,4)]
>>>len(B[0])
7
>>>len(B[1])
3
>>>len(B[2])
5

我现在这样试过:

import sys, os
import os.path

txtdir = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(txtdir, 'txt/')

textfile = "%sfile.txt" % (path)
with open(textfile,"r") as f:
# read a LIST of rows into "data"
data = f.readlines()

previous_col = ''
current_col = ''
for row in data:
match_1 = "(*) Begin"
match_2 = "(*) End"
if (match_1 in row or match_2 in row):
col = row.split()
print col
print len(col)

if (col[3] == "End"):
previous_col = col[1]
elif (col[3] == "Begin"):
current_col = col[1]

i = 0
if current_col:
if (col[3] == "Begin" and current_col == previous_col):
i += 1 # increment
col[3] = "Begin [%s]" % (i)
else:
col[3] = "Begin [0]"

# and write everything back
with open(textfile, 'w') as f:
f.writelines( data )

# close f file
f.close()

但是“file.txt”没有变化

你能给我一些建议吗?

非常感谢,

里卡多

最佳答案

除了 Paul Lo 指出的您根本没有更新 data 列表的明显问题外,我认为您使这些东西过于复杂,您只需使用 collections.Counter 即可完成此操作:

from collections import Counter

c = Counter()

with open('file.txt') as f, open('outfile.txt', 'w') as out:
for line in f:
# In `if` and `elif`, use the current value of the counter
# for the second column, default is 0.
if '(*) Begin' in line:
text = line.split(None, 2)[1]
out.write('{}[{}]\n'.format(line.strip(), c[text]))
elif '(*) End' in line:
text = line.split(None, 2)[1]
out.write('{}[{}]\n'.format(line.strip(), c[text]))
# End found, so now increment the counter
c[text] += 1
else:
out.write(line)

另外,要就地修改同一个文件,我建议使用 fileinput 模块:

from collections import Counter
import fileinput

c = Counter()

for line in fileinput.input('file1.txt', inplace=True):
if '(*) Begin' in line:
text = line.split(None, 2)[1]
print '{}[{}]'.format(line.strip(), c[text])
elif '(*) End' in line:
text = line.split(None, 2)[1]
print '{}[{}]'.format(line.strip(), c[text])
# End found, so now increment the counter
c[text] += 1
else:
print line,

输出:

0   A   (*) Begin[0]
1 A
2 A
3 A
4 A
5 A (*) End[0]
0 B (*) Begin[0]
1 B
2 B
3 B
4 B
5 B
6 B (*) End[0]
0 B (*) Begin[1]
1 B
2 B (*) End[1]
0 B (*) Begin[2]
1 B
2 B
3 B
4 B (*) End[2]

关于python - 集合中的索引中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28302567/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com