gpt4 book ai didi

Python获取多个逗号后面的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 07:08:44 24 4
gpt4 key购买 nike

问题是我需要读取一个 text.txt 文件并从中获取非常具体的数据。该 text.txt 的条目如下所示

b(1,4,8,1,4,TEST,0,3,AAAA,Test,2-150,000)
a(1,1,3,1,3,BBBB,0,3,BBBB,Test,2-150,000)
a(1,0,2,1,4,TEST,0,3,CCCC,Test,2-150,000)
b(1,1,0,1,4,TEST,0,3,DDDD,Test,2-150,000)

所以现在我只需要那些带有“a(”的行,在那些行中我只需要在 5 和 8 逗号之后添加字符串,所以在第 2 行中它将是 BBBB ,BBBB

到目前为止我的代码是:

infile = open("text.txt","r") 
numlines = 0
found = []

for line in infile:
numlines += 1
if "a" in line:
line=line[line.find("(")+1:line.find(")")]
found.append(line.split(','))

wordLed=len(found)
for i in range(0,wordLed):
print found[i]


infile.close()

这只是给了我在“,”处分隔的完整行,但我如何通过它们建立索引?

最佳答案

快速 和脏:

with open('text.txt') as f:
result = [line.split(',')[5:9:3] for line in f if line.startswith("a(")]
# ^^^^^^^
# "5 to 9 (excl.) by step of 3"
# that is items 5 and 5+3
#
# replace by [5] if you only want the fifths item
# replace by [5:9] if you want items from 5 to 9 (excl.)

from pprint import pprint
pprint(result)

因为缺少错误处理...

...无论如何,根据您的样本数据,这会产生:

[['BBBB', 'BBBB'], ['TEST', 'CCCC']]

关于Python获取多个逗号后面的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25507775/

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