×

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

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

Python String swapcase() method

Python String swapcase() method The string.swapcase() method in Python returns a copy of the string with uppercase characters converted to lowercase and vice versa. Syntax string.swapcase() Parameter NA Return This method returns a copy of the 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.

Comments in the Python Programming Language

In this tutorial, we will learn how to comment in multiple lines and paragraphs in the python programming language. Commenting a Paragraph in Python Most people think the importance of comments is...

2 minutes read.

Exclusive OR in Python

In Python, the exclusive OR (XOR) operator is represented by the caret symbol (^). It compares each bit of the first operand to the corresponding bit of the second operand,...

3 minutes read.

Reverse a Number in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

Python Array

Python Array In the programming language or computer science, an array is defined as the form of a data structure which consists of or store collection of various types of elements...

10 minutes read.

Find key from value in dictionary python

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

5 minutes read.

How to Add Elements in List in Python?

How to Add Elements in List in Python We all are aware of the wide spectrum of applications where the data structures of Python are used. Be it lists, tuples, or...

4 minutes read.

Python divmod() function

Python divmod() function The divmod() function in Python returns a tuple containing the quotient  and the remainder when parameter ‘a’ (divident) is divided by parameter ‘b’ (divisor). Syntax: divmod(a, b) Parameter a: This parameter represents a number you...

1 minute read.

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,...

3 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Python delattr() function

Python delattr() function The delattr() function in Python is used to delete the named attribute from the object, with the prior permission of the object. Syntax delattr(object, name) Parameter object : This parameter represents the object from which...

1 minute read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

PyPi TensorFlow

It is a free open-source library for high-performative numerical computations. The architecture of TensorFlow allows us for easy deployment and computing across a varied number of platforms and from desktops...

3 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Python String count() method

Python String count() method The string.count() method returns the number of times a specified value appears in the string. Syntax string.count(sub[, start[, end]]) Parameter sub: This parameter represents a substring to be searched. start: This parameter...

1 minute read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.