Skip to main content
 首页 » 编程设计

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

2025年05月04日18lyj

问题是我需要读取一个 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']]