我编写了一些可以将字符串解析为元组的代码:
s = '30M3I5X'
l = []
num = ""
for c in s:
if c in '0123456789':
num = num + c
print(num)
else:
l.append([int(num), c])
num = ""
print(l)
即;
'30M3I5X'
成为
[[30, 'M'], [3, 'I'], [5, 'X']]
那部分工作正常。然而,我现在正在努力解决如何从标签分隔值文件的第一列获取值以成为我的新's'。即;对于看起来像这样的文件:
# File Example #
30M3I45M2I20M I:AAC-I:TC
50M3X35M2I20M X:TCC-I:AG
某种程度上会有一个循环结合起来只占第一列,产生
[[30, 'M'],[3, 'I'],[45, 'M'],[2, 'I'],[20, 'M']]
[[50, 'M'],[3, 'X'],[35, 'M'],[2, 'I'],[20, 'M']]
没有必须使用
import csv
或任何其他模块。
非常感谢!
答案 0 :(得分:0)
只需open文件的路径并遍历记录?
def fx(s):
l=[]
num=""
for c in s:
if c in '0123456789':
num=num+c
print(num)
else:
l.append([int(num), c])
num=""
return l
with open(fp) as f:
for record in f:
s, _ = record.split('\t')
l = fx(s)
# process l here ...
答案 1 :(得分:0)
以下代码可用于您的目的
rows = ['30M3I45M2I20M I:AAC-I:TC', '30M3I45M2I20M I:AAC-I:TC']
for row in rows:
words = row.split(' ')
print(words[0])
l = []
num = ""
for c in words[0]:
if c in '0123456789':
num = num + c
else:
l.append([int(num), c])
print(l)
根据需要将row.split('')更改为('\ t')或任何其他分隔符
答案 2 :(得分:0)
这样的事情应该做你想要的。
filename = r'\path\to\your\file.txt'
with open(filename,'r') as input:
for row in input:
elements = row.split()
# processing goes here
elements [0]包含作为文件中第一列数据的字符串。
编辑:
最终得到已处理数据列表的列表:
result = []
filename = r'\path\to\your\file.txt'
with open(filename,'r') as input:
for row in input:
elements = row.split()
# processing goes here
result.append(l) # l is the result of your processing
答案 3 :(得分:0)
所以这就是最终为我工作的东西 - 从每个人那里得到点点滴滴,谢谢大家!
注意:我知道它有点冗长,但由于我是新手,它可以帮助我跟踪所有事情:)
#Defining the parser function
def col1parser(col1):
l = []
num = ""
for c in col1:
if c in '0123456789':
num = num + c
else:
l.append([int(num), c])
num = ""
print(l)
#Open file, run function on column1
filename = r'filepath.txt'
with open(filename,'r') as input:
for row in input:
elements = row.split()
col1 = elements[0]
l = col1parser(col1)