473,396 Members | 1,900 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Replacing string with words from a list

I'm having a lot of trouble with the following task for one of my assignments in python. Basically I need to take the user input and replace any words in the input and replace them with words from a list if they are in it. Here's an example

list_of_words = \
[
[['Hi', "G'day", 'Hey'], 'Hello'],
[['Bye', 'Farewell', 'Later', 'Ciao', 'Quit'], 'Goodbye'],
[['Nope', 'Nah'], 'No']
]

So if the user types 'Hi, how are you', they should get in return 'Hello how are you'

The example list that I need to work with is the same layout, but much larger, so I didn't think it would be necessary to post it all here.

I think I know how to approach this, but keep messing up. I tried to use a for loop to say for words that the user types, if they are in the list_of_words, replace them with the line they are on and the second part of the list. I have split up the users input into a list, so the loop should just iterate through each item in that list I'd imagine. We've been told to not use .replace() by the way.

I've tried to use a counter to make the loop go to a different line in the list each time, but don't think that's the way to go. I think I need to do a loop inside a loop, but I get confused. Any pointers to show me in the right direction would be appreciated.
May 7 '08 #1
7 4680
bvdet
2,851 Expert Mod 2GB
I'm having a lot of trouble with the following task for one of my assignments in python. Basically I need to take the user input and replace any words in the input and replace them with words from a list if they are in it. Here's an example

list_of_words = \
[
[['Hi', "G'day", 'Hey'], 'Hello'],
[['Bye', 'Farewell', 'Later', 'Ciao', 'Quit'], 'Goodbye'],
[['Nope', 'Nah'], 'No']
]

So if the user types 'Hi, how are you', they should get in return 'Hello how are you'

The example list that I need to work with is the same layout, but much larger, so I didn't think it would be necessary to post it all here.

I think I know how to approach this, but keep messing up. I tried to use a for loop to say for words that the user types, if they are in the list_of_words, replace them with the line they are on and the second part of the list. I have split up the users input into a list, so the loop should just iterate through each item in that list I'd imagine. We've been told to not use .replace() by the way.

I've tried to use a counter to make the loop go to a different line in the list each time, but don't think that's the way to go. I think I need to do a loop inside a loop, but I get confused. Any pointers to show me in the right direction would be appreciated.
You will need two loops. One to check each word in the sentence entered, and another to look at each element in list_of_words. You will also need to strip punctuation from each word, and capitalize the entered words.

Split the entered phrase with string method split().
Use built-in function enumerate() to iterate on each word in the split phrase.
Iterate on each element in list_of_words.
Expand|Select|Wrap|Line Numbers
  1.     if word.strip(string.punctuation).capitalize() in elem[0]:
If the word is found, assign elem[1] to the corresponding position in the split phrase.
Use string method join() to rejoin the modified split phrase.
HTH
-BV
May 7 '08 #2
micmast
144 100+
If you cannot use replace I would indeed split the string the user inputs, and then loop it
Expand|Select|Wrap|Line Numbers
  1. sentence = input.split(' ')
  2. output = ''
  3. for word in sentence:
  4.   for entry in list_of_words:
  5.     # the first line with possible words
  6.     words_to_replace = entry[0]
  7.     word_to_change_to = entry[1]
  8.     for word_to_replace in words_to_replace:
  9.        # Every word seperately
  10.       if word == word_to_replace:
  11.          # so the word is the same, so we change it
  12.           output = output + ' ' + word_to_change_to
  13.       else:
  14.          # we don't need to change this word.
  15.           output = output + ' ' + word
  16.  
  17. print output
  18. # the sentence should have changed :)
  19.  
  20.  
the code is probably not 100% correct but it will give you an idea
May 7 '08 #3
jlm699
314 100+
It would really help us here if you posted the code that you tried along with the errors that you have recieved. Then we will be able to help you find and fix your errors.
May 7 '08 #4
Thanks a lot for the replys, they really helped. Here's my updated code now..

Expand|Select|Wrap|Line Numbers
  1.  
  2. list_of_words = \
  3. [
  4. [['Hi', "G'day", 'Hey'], 'Hello'],
  5. [['Bye', 'Farewell', 'Later', 'Ciao', 'Quit'], 'Goodbye'],
  6. [['Nope', 'Nah'], 'No']
  7. ]
  8. punctuation_marks = ['?', ',', '!', '.']
  9.  
  10. def standardise_phrase(enter_phrase):
  11.  
  12.  
  13.     for punctuation in punctuation_marks:
  14.         if punctuation in enter_phrase:
  15.             enter_phrase = enter_phrase.replace(punctuation, '')
  16.     split_user_input = enter_phrase.split()
  17.  
  18.  
  19.  
  20.     output = ''
  21.     for word in split_user_input:
  22.  
  23.         for entry in list_of_words:
  24.  
  25.             words_to_replace = entry[0]
  26.             word_to_change_to = entry[1]
  27.  
  28.  
  29.             for word_to_replace in words_to_replace:
  30.                 if word == word_to_replace:  
  31.                     output = output + word_to_change_to + ' '
  32.  
  33.         if word not in list_of_words:
  34.             output = output + word + ' '
  35.  
  36.         return output
  37.  
The code works, however it either gives not enough or too many words back depending on weather I have the last 2 lines of code in.

Eg print standardise_phrase('Hi said Jane. Bye said Tom')
will come out as either;
Hello Hi said Jane Goodbye Bye said Tom
or
Hello Goodbye

I've tried some ways of taking out the unwanted words (Hi and Bye in the example), but as you can see in my code, the 3rd last line " if word not in list_of_words:" doesn't work because it can't check the whole list in 1 go I think.

I don't know if it helps, but other code I've tried instead of the 3rd and 2nd last lines that has not worked is..

Expand|Select|Wrap|Line Numbers
  1.         for excess_word in split_user_input:
  2.             if excess_word not in output:
  3.                 if excess_word not in words_to_replace:
  4.                    output = output + excess_word + ' '
  5.  
  6.  
Thanks again.
May 8 '08 #5
jlm699
314 100+
Ok you're problem (as you suspected) lies in the nested for loop where you say "if word not in list_of_words". One thing you could do is place a boolean variable to say whether there was a hit inside the loop checking for replaceable words. This would be initialized to 0 (or False) right after the "for word in user_input". After the word replacing loop, change your "not in" if check to simply check for that variable to be false, in which case you would keep the same thing that's there already...

Oh, also move your return output statement back one indentation (it's returning inside the for loop!)

Expand|Select|Wrap|Line Numbers
  1. for word in split_user_input:
  2.     rplcd = 0
  3.     for entry in list_of_words:
  4.  
  5.         words_to_replace = entry[0]
  6.         word_to_change_to = entry[1]
  7.  
  8.  
  9.         for word_to_replace in words_to_replace:
  10.             if word == word_to_replace:  
  11.                 rplcd = 1
  12.                 output = output + word_to_change_to + ' '
  13.  
  14.     if not rplcd:
  15.         output = output + word + ' '
  16.  
  17. return output
  18.  
HTH!
May 8 '08 #6
bvdet
2,851 Expert Mod 2GB
Following is an example solution that I worked up.
Expand|Select|Wrap|Line Numbers
  1. import string
  2.  
  3. list_of_words = \
  4. [
  5. [['Hi', "G'day", 'Hey'], 'Hello'],
  6. [['Bye', 'Farewell', 'Later', 'Ciao', 'Quit'], 'Goodbye'],
  7. [['Nope', 'Nah'], 'No']
  8. ]
  9.  
  10. sentence = raw_input("Enter sentence")
  11. sentenceList = sentence.split()
  12.  
  13. for i, word in enumerate(sentenceList):
  14.     for elem in list_of_words:
  15.         if word.strip(string.punctuation).capitalize() in elem[0]:
  16.             sentenceList[i] = elem[1]
  17.  
  18. print ' '.join(sentenceList)
HTH
-BV
May 8 '08 #7
Thanks a bunch jlm699 and bvdet, that got the duplicates not entered into the list.

Thanks!
May 10 '08 #8

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

Similar topics

22
by: ineedyourluvin1 | last post by:
Hello all! I've been looking for a way to strip characters from strings such as a comma. This would be great for using a comma as a delimiter. I show you what I have right now. ...
3
by: dumbledad | last post by:
Hi All, I'm confused by how to replace a SELECT statement in a SQL statement with a specific value. The table I'm working on is a list of words (a column called "word") with an index int...
2
by: Jazzdrums | last post by:
Hello, I've (parts of ) HTML documents and a list of words that I have to transform as an hyperlinks, i.e. surround them with a "<a href="...">" "</a>". A first simple approach is to parse the...
0
by: leeonions | last post by:
Hi there, i am trying to use regular expressions to search through a text string and replace a given whole word. take the string = "The matsat on the mat!" (bad example i know) i want to...
2
by: leeonions | last post by:
Hi there, i am trying to use regular expressions to search through a text string and replace a given whole word. take the string = "The matsat on the mat!" (bad example i know) i want to...
23
by: comp.lang.tcl | last post by:
I have a TCL proc that needs to convert what might be a list into a string to read consider this: ]; # OUTPUTS Hello World which is fine for PHP ]; # OUTPUT {{-Hello}} World, which PHP...
7
by: aine_canby | last post by:
Hi, Im totally new to Python so please bare with me. Data is entered into my program using the folling code - str = raw_input(command) words = str.split() for word in words:
2
by: Zethex | last post by:
At the moment i'm doing a piece of work for school and I'm stuck at the moment. I have a list of words, for example: Sentence = I have another list which I need to use to replace certain...
3
by: Bouzy | last post by:
I have a list of words and am trying to replace all the numbers in my list with whitespace. for word in words: numbers = re.search('+', word) word = clearup(word) if word in...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...

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.