Search code examples
pythonlistnltktokenizecpu-word

How to tokenize a list of words using nltk?


I have a text dataset. Those dataset consist of many lines that each lines are consist of two sentences split by tab, like this :

this is string 1, first sentence.    this is string 2, first sentence.
this is string 1, second sentence.    this is string 2, second sentence.

and then I have split the datatext by this code :

#file readdata.py
from globalvariable import *
import os


class readdata:
    def dataAyat(self):
        global kalimatayat
        fo = open(os.path.join('E:\dataset','dataset.txt'),"r")
        line = []
        for line in fo.readlines():
            datatxt = line.rstrip('\n').split('\t')
            newdatatxt = [x.split('\t') for x in datatxt]
            kalimatayat.append(newdatatxt)
            print newdatatxt

readdata().dataAyat()

it works and the output is :

[['this is string 1, first sentence.'],['this is string 2, first sentence.']]
[['this is string 1, second sentence.'],['this is string 2, second sentence.']]

what I want to do is tokenize those list using nltk word tokenize, and the output I expect is like this :

[['this' , 'is' , 'string' , '1' , ',' , 'first' , 'sentence' , '.'],['this' , 'is' , 'string' , '2' , ',' , 'first' , 'sentence' , '.']]
[['this' , 'is' , 'string' , '1' , ',' , 'second' , 'sentence' , '.'],['this' , 'is' , 'string' , '2' , ',' , 'second' , 'sentence' , '.']]

anybody knows how to tokenize to be like the output above? I want to code a tokenize function in "tokenizer.py" and call it all in "mainfile.py"


Solution

  • To tokenize the list of sentences, iterate over it and store the results in a list:

    data = [[['this is string 1, first sentence.'],['this is string 2, first sentence.']],
    [['this is string 1, second sentence.'],['this is string 2, second sentence.']]]
    results = []
    for sentence in data:
        sentence_results = []
        for s in sentence:
            sentence_results.append(nltk.word_tokenize(sentence))
        results.append(sentence_results)
    

    results will be something like

    [[['this' , 'is' , 'string' , '1' , ',' , 'first' , 'sentence' , '.'],  
      ['this' , 'is' , 'string' , '2' , ',' , 'first' , 'sentence' , '.']], 
    [['this' , 'is' , 'string' , '1' , ',' , 'second' , 'sentence' , '.'],
      ['this' , 'is' , 'string' , '2' , ',' , 'second' , 'sentence' , '.']]]