Python|在字符串列表中标记字符串
有时,在处理数据时,我们需要对可能作为输入作为字符串列表获得的字符串执行字符串标记化。这在机器学习的许多应用中都有用例。让我们讨论一些可以做到这一点的方法。
方法 #1:使用列表理解 + split()
我们可以使用列表推导来遍历字符串列表中的每个字符串,然后拆分函数执行标记化任务,从而实现这一特定任务。
# Python3 code to demonstrate
# Tokenizing strings in list of strings
# using list comprehension + split()
# initializing list
test_list = ['Geeks for Geeks', 'is', 'best computer science portal']
# printing original list
print("The original list : " + str(test_list))
# using list comprehension + split()
# Tokenizing strings in list of strings
res = [sub.split() for sub in test_list]
# print result
print("The list after split of strings is : " + str(res))
The original list : [‘Geeks for Geeks’, ‘is’, ‘best computer science portal’]
The list after split of strings is : [[‘Geeks’, ‘for’, ‘Geeks’], [‘is’], [‘best’, ‘computer’, ‘science’, ‘portal’]]
方法 #2:使用map() + split()
这是可以解决此特定任务的另一种方法。在这个方法中,我们只是执行与上面类似的任务,只是我们使用 map函数将拆分逻辑绑定到整个列表。
# Python3 code to demonstrate
# Tokenizing strings in list of strings
# using map() + split()
# initializing list
test_list = ['Geeks for Geeks', 'is', 'best computer science portal']
# printing original list
print("The original list : " + str(test_list))
# using map() + split()
# Tokenizing strings in list of strings
res = list(map(str.split, test_list))
# print result
print("The list after split of strings is : " + str(res))
The original list : [‘Geeks for Geeks’, ‘is’, ‘best computer science portal’]
The list after split of strings is : [[‘Geeks’, ‘for’, ‘Geeks’], [‘is’], [‘best’, ‘computer’, ‘science’, ‘portal’]]
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。