我试图为一些NLP编写一个python中字符串标记化的代码,并产生了以下代码:
str = ['I am Batman.','I loved the tea.','I will never go to that mall again!']
s= []
a=0
for line in str:
s.append([])
s[a].append(line.split())
a+=1
print(s)
结果是:
[[['I', 'am', 'Batman.']], [['I', 'loved', 'the', 'tea.']], [['I', 'will', 'never', 'go', 'to', 'that', 'mall', 'again!']]]
如您所见,列表现在有一个额外的维度,例如,如果我想要单词“蝙蝠侠”,我必须键入s[0][0][2]
而不是s[0][2]
,因此我将代码更改为:
str = ['I am Batman.','I loved the tea.','I will never go to that mall again!']
s= []
a=0
m = []
for line in str:
s.append([])
m=(line.split())
for word in m:
s[a].append(word)
a += 1
print(s)
得到了正确的结果:
[['I', 'am', 'Batman.'], ['I', 'loved', 'the', 'tea.'], ['I', 'will', 'never', 'go', 'to', 'that', 'mall', 'again!']]
但是我觉得这可以用一个循环来实现,因为我要导入的数据集会非常大,n
的复杂性会比n^2
好得多,那么,有没有更好的方法来实现这一点/用一个循环来实现这一点的方法呢?你知道吗
循环中的每个字符串都应该使用
split()
列表理解示例:
看到了吗本文件:你知道吗
你原来的代码就快到了。你知道吗
line.split()
给你一个列表,所以把它附加到你的循环中。 或者直接去理解:当你说
s.append([])
时,索引“a”处有一个空列表,如下所示:如果您将
split
的结果附加到它上面,比如L.append([1])
,您将得到这个列表中的一个列表:[[1]]
相关问题 更多 >
编程相关推荐