python 拆分行并去掉 ;

0 投票
3 回答
1276 浏览
提问于 2025-04-18 01:41

我有一个tsv文件,我想把列表中的分号(;)去掉,但每次都出现错误信息“AttributeError: 'list' object has no attribute 'split'”。

  import csv

  h = []
  with open('paths_finished.tsv', 'rb') as csvfile:
  ar = csv.reader(csvfile, dialect='excel-tab')

  for row in ar:

      h.append(row[3:4].split(';'))

  print h

输出:

   ['14th_century;15th_century;16th_century]

我该怎么在这个输出中分割分号(;)呢?

3 个回答

0

试试这个,

>>> ''.join(a)
'14th_century;15th_century;16th_century'
>>> a=''.join(a)
>>> a
'14th_century;15th_century;16th_century'
>>> a.split(';')
['14th_century', '15th_century', '16th_century']
0

你可以这样做:

>>> my_output = ['14th_century;15th_century;16th_century']   #this is your current output

>>> print my_output[0].split(';')
['14th_century', '15th_century', '16th_century']

这段代码会取你上面输出的第一个元素,然后根据字符串中用';'分隔的部分来打印列表。

1

row 是一个列表,所以用 row[3:4] 这个切片得到的也是一个列表。

你只需要用 row[3] 就可以直接获取列表中的那个(字符串)项。

for row in ar:
      h.append(row[3].split(';'))

你也可以使用列表推导式来处理。

import csv

with open('paths_finished.tsv', 'rb') as csvfile:
    ar = csv.reader(csvfile, dialect='excel-tab')
    h = [row[3].split(';') for row in ar if len(row) > 3]

print h

撰写回答