python - 不断收到错误 'list' 对象没有属性 'split'

标签 python python-2.7

当尝试逐字、逐行拆分我的列表时,不断出现此拆分错误。

我得到了一个包含链接的文件,+20000 个链接。这些链接位于名为“链接”的列表中

到目前为止我的代码:

import networkx as nx

# Create graph
network_graph = nx.Graph()

path = []
with open('paths_finished.tsv','r') as tsv:
    paths = [line.strip().split('\t') for line in tsv]  
    newPath = paths[16:]


links = []    
for line in newPath:
    links.append(line[3:4])

newList = []

for i in links:
    newList.append(i.split(';'))

print newList

链接列表的长度 = 51318。 我想拆分列表中每个链接中的“;”。

例如文件中的第一个链接是:

['14th_century;15th_century;16th_century;Pacific_Ocean;Atlantic_Ocean;Accra;Africa;Atlantic_slave_trade;African_slave_trade'], 

然后我想逐字拆分它,所以我得到了:

['14th_century 15th_century 16th_century Pacific_Ocean Atlantic_Ocean Accra Africa Atlantic_slave_trade African_slave_trade'], 

最佳答案

首先 - 正如 Martijn Pieters 所说,你的缩进已经关闭。很难准确猜出你的意思,请修正它。但是:

paths = [line.strip().split('\t') for line in tsv]  

line.split('\t') 已经返回一个列表。您将该列表放入 path 中,因此 path 是一个列表列表。您可以在此处迭代该列表的列表:

for line in newPath:
   links.append(line[3:4])

因此链接也将是列表的列表。最后:

for i in links:
   newList.append(i.split(';'))

您尝试为 i 调用 split - 这是一个列表。 split 是 str 的成员函数,对于列表不存在 - 因此您的错误。

关于python - 不断收到错误 'list' 对象没有属性 'split',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22909851/

相关文章:

python - 在特定的一个数据集上出现此错误

Python Urllib2 只读文档的一部分

python - 如何从 django.utils.safestring.SafeText 获取字符串

python - 重复 NumPy 数组而不复制数据?

python - Xlsxwriter 根据 if 语句更改格式颜色

python - 在 Django 中返回 HttpResponse 后删除 tmp 文件

ubuntu - LPSolve、Python 和 Ubuntu?

python - pandas dataframe切片产生不同的结果

python - 仅导入模块的某些部分,但将这些部分列为字符串

python-2.7 - 如何在文件 GDB、ArcGIS 中设置工作空间