×

Sentence to python vector

Conversion of a Sentence to Vector in Python

Before starting the tutorial, let’s just recap about the vector and the respective package that has to be imported in Python.

Python Vector:

Putting simply, we can say that vector is an array with single dimension in Python. In order to use vector, Python comes with a built- in module called NumPy. By importing the module we are allowed to create a vector in Python.

Creation of a Vector:

For creating a vector, the Python module provides numpy.array() method , which helps us to create both vertical and horizontal vectors.

Consider the program:

#Python 3
import numpy as np
list_1 = [100, 200, 300, 400, 500]   # horizontal with one row
list_2 = [[10],[11], [12], [13], [14]] # vertical with one column
vector_1= np.array(list_1)
vector_2 = np.array(list_2)
print(“ Horizontal Vector : “)
print(vector_1)
print(“Vertical Vector : “)
print(vector_2)

Output:

Horizontal vector :
[100, 200, 300, 400, 500]
Vertical vector :
[[10],[11], [12], [13], [14]]

We know how to create a vector with the help of the built – in python module NumPy. Now, we are going to convert or store a sentence that can be any text line into vector using Python with its available methods.

We can store a sentence in a vector in two ways: like separating it into words or into characters. In the following example we will consider a string text line and convert it into list by splitting the words with split() method in Python.

#Python 3
import numpy as np
st="welcome to Java T Point"
np.array(list(st.split(" ")))    # splitting the string and converting list of words to vector

Output:

array(['welcome', 'to', 'Java', 'T', 'Point'], dtype='<U7')

Explanation:

  • First we converted the text line into list of words by usual split method  called tokenization, and then converted to NumPy single dimensional array, which we call it as vector.
  • Tokenization involves splitting sequence of strings or sentences into words, phrases and some keywords or symbols (tokens). And also observe the above output, we can see dtype = ’<U7’ which means datatype is Unicode with maximum length 7 (welcome).
  • Data type object or dtype is interpretating fixed block of memory respective to an array. It’s value will be maximum length of all strings present in an array or a vector. Once it is fixed after storing some values , then we cannot insert another string greater than that length. Only, the characters up to the length will be inserted.

Let’s look at another simple program to convert list of sentences to vector.

Example 1:

import numpy as np
arr = ["hello everyone", "this is javatpoint", "you are welcome"]
my=np.asarray (arr, dtype = None, order = None)
np.asarray(arr, dtype=None, order=None)

Output:

array(['hello everyone', 'this is javatpoint', 'you are welcome'],
      dtype='<U18')

Here, we converted a list of sentences to a vector and datatype is none.

We can just do the same thing using different method, as shown in following example.

Example 2:

#Python 3
import numpy as np
arr = [ "hello everyone", "this is javatpoint", "you are welcome" ]
np.array ([i for i in arr])

Output:

array(['hello everyone', 'this is javatpoint', 'you are welcome'],
      dtype='<U18')

We got the same output as the above program as the loop iterates over the list and provides each value to i.

Overview:

  • Vector is a NumPy single dimensional array and creation can be done by numpy.array () method.
  • In order to convert a sentence or sequence of words to a vector, we need to tokenize the text and then generate the vector.
  • The dtype in the vector represents maximum length of an individual string present in the sequence.

Related Topics

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.

Python Key Error

What is an Error? Errors are nothing but problems in the program which occur in a program code, and this will stop the execution of the program. It is also called...

6 minutes read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Python Data Types

Python Data Types: The variable in Python is used to store values, and they can hold different values. Each variable in Python has its own data-type. Since Python is a...

13 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.

Python Program to Check Leap Year

Python Program to Check Leap Year Leap year: We all know that each year has 365 or 366 days. But whenever a year has 366 days, then the year is said...

2 minutes read.

Tuple in Python

Tuples Tuples are the same as the list but as we know that lists are mutable means we can change the data from it. In the tuple we cannot change the...

6 minutes read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

How to read data from com port in python

Comport, the I/O interface is known as a COM port that allows the connection for a serial device to a computer. COM ports are sometimes referred to as serial ports....

3 minutes read.

XXhash Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

6 minutes read.

apply() function in python

Pandas: Pandas is a library in python. It is an open source package in python. Pandas in python are used for data cleaning and data analysis. Data frame mainly consists of...

3 minutes read.

How to Download Python

How to Download Python Python is the most renowned programming language and developers across the globe are working on projects that are made using Python and its libraries. Here we will...

4 minutes read.

File Explorer using Tkinter in Python

File Explorer: Users can control folders and files on a device using an application known as a file manager or file explorer. Customers can access, edit, copy, delete, and start moving files...

3 minutes read.

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

Python range() function

Python range() function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Syntax range(stop)        or range(start, stop[, step]) Parameter start: It is...

1 minute read.

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.