gpt4 book ai didi

python - python 如何仅使用文件中每一行的最后一部分?

转载 作者:行者123 更新时间:2023-11-30 23:13:39 25 4
gpt4 key购买 nike

#!/usr/bin/python

import sys, re

fname = sys.argv[1]
barcodefname = sys.argv[2]

barcodefile = open(barcodefname, "r")
#list = open(barcodefname, "r").readlines(-1)

for barcode in barcodefile:
barcode = barcode.strip()
print "barcode: %s" % barcode
outfname = "%s.%s" % (fname, barcode)
outf = open(outfname, "w")
handle = open(fname, "r")
for line in handle:
potential_barcode = line[:len(barcode)]
if potential_barcode == barcode:
outseq = line[len(barcode):]
sys.stdout.write(outseq)
outf.write(outseq)
handle.close()
outf.close()
barcodefile.close()

我遇到的问题是第二个参数文件看起来像这样:

S1 djgbfgbf
S2 dkffbjfb
S3 lfjbvrid
....etc

我需要找到一种方法来忽略每行开头的 S1、S2、S3,只将以下字母与参数 1 文件匹配。在第 9 行,我正在尝试以某种方式创建一个列表并反转它,但我不确定这是否是答案。

最佳答案

对于像 S1 djgbfgbf 这样的字符串,如果您想忽略第一部分,您可以拆分字符串并选择最后一项,并且该字符串也可以是文件的一行:

>>> s='S1 djgbfgbf'
>>> s.split()[-1]
'djgbfgbf'

例如,如果您有一个名为 in_file 的文件,您可以执行以下列表理解,其结果是所有行的最后一部分:

[line.split()[-1] for line in open('in_file')]

或者你可以循环你的文件(比列表理解效率低,但可以更灵活):

for line in open('in_file'):
last_part=line.split()[-1]
#do stuff with last part

关于python - python 如何仅使用文件中每一行的最后一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29204505/

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