Python | Tokenizing strings in list of strings

Sometimes, while working with data, we need to perform the string tokenization of the strings that we might get as an input as list of strings. This has a usecase in many application of Machine Learning. Let’s discuss certain ways in which this can be done.

Method #1 : Using list comprehension + split()

We can achieve this particular task using list comprehension to traverse for each strings from list of strings and split function performs the task of tokenization.



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

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’]]

 

Method #2 : Using map() + split()
This is yet another method in which this particular task can be solved. In this method, we just perform the similar task as above, just we use map function to bind the split logic to the entire list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

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’]]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.