有没有更好的方法来标记一些字符串?

2024-03-29 12:37:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为一些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好得多,那么,有没有更好的方法来实现这一点/用一个循环来实现这一点的方法呢?你知道吗


Tags: thetogothatlineamwillagain
3条回答

循环中的每个字符串都应该使用split()

列表理解示例:

str = ['I am Batman.','I loved the tea.','I will never go to that mall again!']

[s.split() for s in str]

[['I', 'am', 'Batman.'],
 ['I', 'loved', 'the', 'tea.'],
 ['I', 'will', 'never', 'go', 'to', 'that', 'mall', 'again!']]

看到了吗本文件:你知道吗

>>> list1 = ['I am Batman.','I loved the tea.','I will never go to that mall again!']
>>> [i.split() for i in list1]  
# split by default slits on whitespace strings and give output as list

[['I', 'am', 'Batman.'], ['I', 'loved', 'the', 'tea.'], ['I', 'will', 'never', 'go', 'to', 'that', 'mall', 'again!']]

你原来的代码就快到了。你知道吗

>>> str = ['I am Batman.','I loved the tea.','I will never go to that mall again!']
>>> s=[]
>>> for line in str:
...   s.append(line.split())
...
>>> print(s)
[['I', 'am', 'Batman.'], ['I', 'loved', 'the', 'tea.'], ['I', 'will', 'never', 'go', 'to', 'that', 'mall', 'again!']]

line.split()给你一个列表,所以把它附加到你的循环中。 或者直接去理解:

[line.split() for line in str]

当你说s.append([])时,索引“a”处有一个空列表,如下所示:

L = []

如果您将split的结果附加到它上面,比如L.append([1]),您将得到这个列表中的一个列表:[[1]]

相关问题 更多 >