473,799 Members | 2,950 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Split function to split sentence into words

11 New Member
Hi,

i don't have enough experience in writing codes in Python but now i'm trying to see how i can start using Python.
I've tried to write a simple program that can display a sentence. now my problem is how to write a code using split function to split that sentence into words then print out each word separately. let me give u an example:

>>>sentence=" My question is to know how to write a code in Python"

then the output of this sentece must give:

sentence[1]=My
sentence[2]=question
sentence[3]=is
sentence[4]=to
sentence[5]=know
......
.......

Can someone help me in this?
Nov 15 '08 #1
19 66227
oler1s
671 Recognized Expert Contributor
Always check the documentation, for something interesting. In this case, look at possible string methods ( http://www.python.org/doc/2.5.2/lib/string-methods.html ) and you will see a split function. Here’s a quick example.
Expand|Select|Wrap|Line Numbers
  1. >>> sent = "Jack ate the apple."
  2. >>> splitsent = sent.split(' ')
  3. >>> splitsent
  4. ['Jack', 'ate', 'the', 'apple.']
Simple as that.
Nov 15 '08 #2
fellya
11 New Member
thank you for the help but the question is not fully answered! with this program it will split the sentence but i would like the output to be lets say if we have a= jack ate the apple, i would like the output to be:
a[0]=jack
a[1]=ate
a[2]=the
a[3]=apple

can you please see if its possible to get the above output?
Nov 15 '08 #3
bvdet
2,851 Recognized Expert Moderator Specialist
thank you for the help but the question is not fully answered! with this program it will split the sentence but i would like the output to be lets say if we have a= jack ate the apple, i would like the output to be:
a[0]=jack
a[1]=ate
a[2]=the
a[3]=apple

can you please see if its possible to get the above output?
The answer is: string formatting!

Example:
Expand|Select|Wrap|Line Numbers
  1. >>> sentence = "The dog ate my homework"
  2. >>> for i,word in enumerate(sentence.split()):
  3. ...     print "Word #%d: %s" % (i, word)
  4. ...     
  5. Word #0: The
  6. Word #1: dog
  7. Word #2: ate
  8. Word #3: my
  9. Word #4: homework
  10. >>> 
Nov 15 '08 #4
fellya
11 New Member
thank you for the help, but as u can see with the output below when i do the command sentence[0] to show me the first word it is showing me "T" this is not what i want!!! for me i would like to see if i type the command sentence[0]; to display "The" and if i type again sentence[1]; it has to give me "dog"


can you plz help!
Expand|Select|Wrap|Line Numbers
  1. >>> sentence="The dog ate my homework"
  2. >>> for i, word in enumerate(sentence.split()):
  3. ...             print " word #%d: %s" % (i,word)
  4. ...
  5.  word #0: The
  6.  word #1: dog
  7.  word #2: ate
  8.  word #3: my
  9.  word #4: homework
  10. >>> sentence[0]
  11. 'T'
  12. >>> sentence[1];
  13. 'h'
  14. >>>
  15.  
Nov 16 '08 #5
bvdet
2,851 Recognized Expert Moderator Specialist
How about this?
Expand|Select|Wrap|Line Numbers
  1. >>> split_sentence = sentence.split()
  2. >>> split_sentence[0]
  3. 'The'
  4. >>> split_sentence[1]
  5. 'dog'
  6. >>> 
Nov 16 '08 #6
fellya
11 New Member
ohhhh thank you so much.
thats what i wanted.
may God bless U.
once again thank you
Nov 16 '08 #7
fellya
11 New Member
hi, i have another question related to the above:
I have created a file of more than 100 sentences in it then i saved it with extension .py , then i'm using the operations to open the file which are:
Expand|Select|Wrap|Line Numbers
  1. f=open("example.py")
  2. try:
  3.     for line in f:
  4.                     print line
  5. finally:
  6.           f.close()
  7.  
so after using the above commands im able to open my file. Now i know how to split a sentence into words, the problem comes now how can i do it on a file containing more than 100 sentences in it? with 1 or 2 senteces i can write the sentences and split them, now how about a file with many sentences?

can someone help me?
Nov 16 '08 #8
bvdet
2,851 Recognized Expert Moderator Specialist
Please use code tags around code. It will make your code much easier to read.

[CODE]..code goes here..[/CODE]

In your code, you are iterating on each line in the file. Each iteration, the variable line represents a sentence. Do you want to save the sentence in a list? What do you want to do with 100 sentences?

The following will save a list of lists. You can access each word by list index.
Expand|Select|Wrap|Line Numbers
  1. lineList = [line.strip().split() for line in open("your_file").readlines()]
  2. # print the first word in the first line.
  3. print lineList[0][0]
Nov 16 '08 #9
fellya
11 New Member
i dont need to save a sentence in a list. what i want to do is : i take a document which has like any number of sentences then by using Python i would like to split the document of any number of sentences into words where each word has a number e.g., word1=the, word2= apple ect. then by this output i will use an other program that can help me to identify if word1 is a noun or not and son on. Brief after getting all the words in a document , I will try to identify only noun and extract only nouns from the doc.
Nov 16 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

5
7567
by: Arjen | last post by:
Hi All, What I want to is using a string as PATTERN in a split function. This makes it possible for me to change the PATTERN on one place in my script... For example: $separator = ";"; $line = "field1;value1"; local($field, $value) = split(/$separator/, $line);
5
4058
by: NewToThis | last post by:
I am trying to use the split function to bread up lines in a file I am reading from. Some lines are working just fine, but a couple of the lines don't split up the way I would have thought. Here's part of the code. Dim strDelim As String = "*~" Dim delimiter As Char() = strDelim.ToCharArray Dim split As String() = Nothing Dim fieldCount As Integer Dim s As String
8
2198
by: Rick | last post by:
I have a program that reads from a file. In the file are a series of words. I read in all the words into a string array, find the average length, count the number of words, display the longest word and how long it is, and display the smallest word and how long it is. All that is working fine, but what I need to do it format certain words that contain a period at the end of them (ex: a word at the end of a sentence), words with quotes...
3
10529
by: Reb | last post by:
Hi, I could split only by a character. How do i split by a string. How can i do something like this. e.g., somestring.Split("name"); Thanks Reb
2
2024
by: Elhanan | last post by:
hi all.. i have the following string: 200850625~01~464~^^200850625~01~464~^^200850625~01~908~^^ which i will need to turn to a mutli-dimentional string array i used result.Split(new char{'^','^'}) for the rows but for some reason i get an empty cell between each result, this is also in the documentation, i just don't know why?
5
2889
by: sck10 | last post by:
Hello, I have a list of email addresses that I need to send email to from the website. I am trying to use the "Split" function to get all the To's and then use the uBound function for the For-Loop limit: I am trying to convert the following from vb to c#: Dim SplitCatcher As Object SplitCatcher = Split(To, ",")
6
3949
by: Xernoth | last post by:
Hi, I have an exercise that requests the following: Write a function that reads words from an input stream and stores them in a vector. Use that function both to write programs that count the number of words in the input, and to count how many times each word occurred.
1
2437
by: John | last post by:
Hi I have written a Split function which in turn calls the standard string split function. Code is below; Function Split1(ByVal Expression As String, Optional ByVal Delimiter As String = " ", Optional ByVal Limit As Integer = -1, Optional ByVal Compare As CompareMethod = CompareMethod.Binary, Optional ByVal MaxLength As Integer = 0) As String()
3
4283
by: Jonas Peter | last post by:
Hi guys, I have got a question that I would love for you guys to give me an idea on how to get started with. First of all, I'm using Windows 7 and Python 2.7 I've got a text file and im trying to read the text from that file and then check every word with 40 words around that word, to make sure the word in question has not been repeated more than once. In other words, I want to first split the text into words, put them in a list and...
0
10250
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10222
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9068
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7564
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4139
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3757
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.