AttributeError: 'list' 对象没有属性 'strip' [英] AttributeError: 'list' object has no attribute 'strip'
本文介绍了AttributeError: 'list' 对象没有属性 'strip'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码导致 AttributeError: 'list' object has no attribute 'strip' 我不知道如何修复它:
The following code is causing AttributeError: 'list' object has no attribute 'strip' and I do not how to fix it:
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
from itertools import groupby
DATA = [["Test", "A", "B01", 828288, 1, 7, 'C', 5],
["Test", "A", "B01", 828288, 1, 7, 'T', 6],
["Test", "A", "B01", 171878, 3, 7, 'C', 5],
["Test", "A", "B01", 171878, 3, 7, 'T', 6],
["Test", "A", "B01", 871963, 3, 9, 'A', 5],
["Test", "A", "B01", 871963, 3, 9, 'G', 6],
["Test", "A", "B01", 1932523, 1, 10, 'T', 4],
["Test", "A", "B01", 1932523, 1, 10, 'A', 5],
["Test", "A", "B01", 1932523, 1, 10, 'X', 6],
["Test", "A", "B01", 667214, 1, 14, 'T', 4],
["Test", "A", "B01", 667214, 1, 14, 'G', 5],
["Test", "A", "B01", 667214, 1, 14, 'G', 6]]
def iter_something(rows):
key_names = ['type', 'name', 'sub_name', 'pos', 's_type', 'x_type']
chr_key_names = ['letter', 'no']
for keys, group in groupby(rows, lambda row: row[:6]):
result = dict(zip(key_names, keys))
result['chr'] = [dict(zip(chr_key_names, row[6:])) for row in group]
yield result
def convert(val):
constructors = [int, str]
for c in constructors:
try:
return c(val)
except ValueError:
pass
def main():
with open("/home/mic/tmp/test.txt") as f:
parts = (line.split(',') for line in f)
column = (part.strip() for part in parts)
for object_ in iter_something(column):
print(object_)
if __name__ == '__main__':
main()
推荐答案
您已将行拆分为列:
parts = (line.split(',') for line in f)
然后尝试剥离每个列列表:
then try to strip each list of columns:
column = (part.strip() for part in parts)
那行不通.改为去除每一列:
That won't work. Strip each column instead:
column = ([col.strip() for col in part] for part in parts)
您可能想要使用 csv
模块 改为进行从文件到数据行的转换:
You may want to use the csv
module to do the transformation from file to row-of-data instead however:
with open("/home/mic/tmp/test.txt", 'rb') as f:
reader = csv.reader(f, skipinitialspace=True)
for object_ in iter_something(reader):
print(object_)
skipinitialspace
选项确保删除紧跟在分隔符之后的空格.理所当然地删除了每行末尾的换行符.
The skipinitialspace
option makes sure that a space directly following the delimiter is removed. A newline at the end of each line removed as a matter of course.
这篇关于AttributeError: 'list' 对象没有属性 'strip'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文