Python Coding for Reversing Sentences - python

this is the code i am using so far.
translated = []
line = input('Line: ')
while line != '':
for word in line.split():
letters = list(word)
letters.reverse()
word = ''.join(letters)
translated.append(word)
if line == '':
print(' '.join(translated))
elif line:
line = input('Line: ')
it is suppose to read lines of input from the user. An empty line is suppose to signify the end of any inputs. Then the program is suppose to read all the lines, then reproduce them in their original order with each word reversed in place.
For example if i was to input: Hello how are you
Its output shout be: olleH woh era uoy
Currently it is asking for the inputs, then stopping when there is an empty line, but not producing anything. No reversed words no nothing.
Can anyone tell me what i am doing wrong, and help me out with my code??

The print statement needs to be outside the loop. Your loop condition ensures that line is never '' inside the loop, so the if condition is never satisfied.
For the same reason, you need to rethink the elif.

as #Flav points out to read all lines before an empty line to end the input. I have edited the solution as below:
lines = [] # to store all line inputs
while True:
line = raw_input('Line: ') # input if using python3 or raw_input if python2.6/7
if line == '':
break
lines.append(line)
for line in lines:
print (' '.join([word[::-1] for word in line.split(' ')]))

You could probably do it like this.
' '.join( [ i[::-1] for i in line.split( ' ' ) ] )
Split the line into words
Reverse each word
Put them back together

The issue is that when the line is empty, your while loop stops. You should get rid of the if / else which are useless here.
Full script:
translated = []
line = input('Line: ')
while line != '':
for word in line.split():
letters = list(word)
letters.reverse()
word = ''.join(letters)
translated.append(word)
#The above for loop could be done in one line with:
#translated.extend([word[::-1] for word in line.split()])
line = input('Line: ')
print(' '.join(translated))

This works perfect
a = "Hello how are you"
" ".join([ "".join(reversed(x)) for x in re.findall('\w+',a) ])

Related

Returning a line of txt.-file that has a word with more than 6 characters and starts with "A" in Python

I have a task to accomplish in Python with only one sentence:
I need to return lines of my txt-file that include words which have more than 6 characters and start with the letter "A".
My code is the following:
[line for line in open('test.txt') if line.split().count('A') > 6]
I am not sure how to implement another command in order to say that my word starts with "A" and has to have more than 6 characters. That is the furthest I could do. I thank you for your time.
Greetings
I would split up your for loop so that it's not a list comprehension, to make it easier to understand what's going on. Once you do that, it should be clearer what you're missing so you can assemble it back into a list comprehension.
lines = []
with open('test.txt', 'r') as f:
for line in f: # this line reads each line in the file
add_line = False
for word in line.split():
if (word.startswith('A') and len(word) > 6):
add_line = True
break
if (add_line):
lines.append(line)
This roughly translates to
[line for line in open('test.txt', 'r') if any(len(word) > 6 and word.startswith('A') for word in line.split())]
You should break each line and compare each word separately
[line for line in open('test.txt') if len([word for word in line.split(' ') if word[0].lower() == 'a' and len(word)> 6]) > 0]

How to fix python not writing to file

I'm making a script that reads a dictionary and picks out words that fit a search criteria. The code runs fine, but the problem is that it doesn't write any words to the file "wow" or print them out. The source for the dictionary is https://github.com/dwyl/english-words/blob/master/words.zip.
I've tried changing the opening of the file to "w+" instead of "a+" but it didn't make a difference. I checked if there just weren't any words that fitted the criteria but that isn't the issue.
listExample = [] #creates a list
with open("words.txt") as f: #opens the "words" text file
for line in f:
listExample.append(line)
x = 0
file = open("wow.txt","a+") #opens "wow" so I can save the right words to it
while True:
if x < 5000: # limits the search because I don't want to wait too long
if len(listExample[x]) == 11: #this loop iterates through all words
word = listExample[x] #if the words is 11 letters long
lastLetter = word[10]
print(x)
if lastLetter == "t": #and the last letter is t
file.write(word) #it writes the word to the file "wow"
print("This word is cool!",word) #and prints it
else:
print(word) #or it just prints it
x += 1 #iteration
else:
file.close()
break #breaks after 5000 to keep it short
It created the "wow" file but it is empty. How can I fix this issue?
This fixes your problem. You were splitting the text in such a way that each word had a line break at the end and maybe a space too. I've put in .strip() to get rid of any whitespace. Also I've defined lastLetter as word[-1] to get the final letter regardless of the word's length.
P.S. Thanks to Ocaso Protal for suggesting strip instead of replace.
listExample = [] #creates a list
with open("words.txt") as f: #opens the "words" text file
for line in f:
listExample.append(line)
x = 0
file = open("wow.txt","a+") #opens "wow" so I can save the right words to it
while True:
if x < 5000: # limits the search because I don't want to wait too long
word = listExample[x].strip()
if len(word) == 11:
lastLetter = word[-1]
print(x)
if lastLetter == "t": #and the last letter is t
file.write(word + '\n') #it writes the word to the file "wow"
print("This word is cool!",word) #and prints it
else:
print(word) #or it just prints it
x += 1 #iteration
else:
print('closing')
file.close()
break #breaks after 5000 to keep it short

Word Frequency Counter Python

Struggling with this exercise which must use a dictionary and count the number of times each word appears in a number of user inputs. It works in a fashion, but does not atomise each word from each line of user input. So instead of counting an input of 'happy days' as 1 x happy and 1 x days, it gives me 1 x happy days. I have tried split() along with the lower() but this converts the input to a list and I am struggling with then pouring that list into a dictionary.
As you may have guessed, I'm a bit of a novice, so all help would be greatly appreciated!
occurrences = {}
while True:
word = input('Enter line: ')
word = word.lower() #this is also where I have tried a split()
if word =='':
break
occurrences[word]=occurrences.get(word,0)+1
for word in (occurrences):
print(word, occurrences[word])
EDIT
Cheers for responses. This ended up being the final solution. They weren't worried about case and wanted the final results sorted().
occurrences = {}
while True:
words = input('Enter line: ')
if words =='':
break
for word in words.split():
occurrences[word]=occurrences.get(word,0)+1
for word in sorted(occurrences):
print(word, occurrences[word])
What you have is almost there, you just want to loop over the words when adding them to the dict
occurrences = {}
while True:
words = input('Enter line: ')
words = words.lower() #this is also where I have tried a split()
if words =='':
break
for word in words.split():
occurrences[word]=occurrences.get(word,0)+1
for word in (occurrences):
print(word, occurrences[word])
This line does not get executed: occurrences[word]=occurrences.get(word,0)+1
Because if it enters the if, it goes to the break and never executes that line. To make it be outside of the if don't indent it.
In general, the indentation of the posted code is messed up, I guess it's not really like that in your actual code.
Do you want line by line stats or do you want overall stats ? I'm guessing you want line by line, but you can also get overall stats easily by uncommenting a few lines in the following code:
# occurrences = dict() # create a dictionary here if yuo want to have incremental overall stats
while True:
words = input('Enter line: ')
if words =='':
break
word_list = words.lower().split()
print word_list
occurrences = dict() # create a dict here if you want line by line stats
for word in word_list:
occurrences[word] = occurrences.get(word,0)+1
## use the lines bellow if you want line by line stats
for k,v in occurrences.items():
print k, " X ", v
## use the lines bellow if you want overall stats
# for k,v in occurrences.items():
# print k, " X ", v

How to get word by word from a string?

For the purpose of sentiment analysis I want to analyse each word in a sentence. I want to store each word in a variable and then process it. I use the following code and i got an error message saying :
Attribute Error: 'list' object has no attribute 'split'
line = ' hello this is a test sentence'
while line:
line=line.split(' ')
print '\n'
What is the solution for above problem?
Here is what happens in your code:
line = "..." - line is a string
while line: - start looping, as non-empty string evaluates to True
line = line.split(" ") - split line by spaces, line is now a list
print '\n' - print a newline character
while line: - non-empty list evaluates True, so loop again
line = line.split(" ") - line is a list, hence AttributeError
I am not sure why you are using a while loop here, you probably want:
for word in line.split(" "):
print word
# ... process word
the issue here is actually when the loop hits its second iteration line is no longer a string. and so the logic says is object line not None if yes, run split on it. However at this point line is now a list.
what you really want is
line = 'hello this is a sentance'
words = line.split()
for w in words:
print w
Here are two ways:
string.split(' ') ?
>>> a="1.MATCHES$$TEXT$$STRING"
>>> a.split("$$TEXT$$")
['1.MATCHES', 'STRING']
>>> a="2.MATCHES $$TEXT$$ STRING"
>>> a.split("$$TEXT$$")
['2.MATCHES ', ' STRING']
and:
>>> [x.strip() for x in "2.MATCHES $$TEXT$$ STRING".split("$$TEXT$$")]
['2.MATCHES', 'STRING']
so whats nice is you don't have to loop, you have have to assign it and use it.
a="my;string;here"
a = a.split(";")
for w in a:
print w
Just split the string once: wordList = line.split()
And use the wordList to iterate over:
for x in wordList:
doWork...
p.s.: I don't quite get why you would print a newline character in each iteration of the loop.

Length function in python is not working the way I want to

I am newbie to programming and python. I looked online for help and I doing as they say but I think I am making a mistake which I am not able to catch.
For now all I'm trying to do here is: if the word matches the length that user entered with the word in the file, make a list of those words. It sort of works if I replace userLength with the actual number but it's not working with variable userlength. I need that list later to develop Hangman.
Any help or recommendation on code will be great.
def welcome():
print("Welcome to the Hangman: ")
userLength = input ("Please tell us how long word you want to play : ")
print(userLength)
text = open("test.txt").read()
counts = Counter([len(word.strip('?!,.')) for word in text.split()])
counts[10]
print(counts)
for wl in text.split():
if len(wl) == counts :
wordLen = len(text.split())
print (wordLen)
print(wl)
filename = open("test.txt")
lines = filename.readlines()
filename.close()
print (lines)
for line in lines:
wl = len(line)
print (wl)
if wl == userLength:
words = line
print (words)
def main ():
welcome()
main()
The input function returns a string, so you need to turn userLength into an int, like this:
userLength = int(userLength)
As it is, the line wl == userLength is always False.
Re: comment
Here's one way to build that word list of words with the correct length:
def welcome():
print("Welcome to the Hangman: ")
userLength = int(input("Please tell us how long word you want to play : "))
words = []
with open("test.txt") as lines:
for line in lines:
word = line.strip()
if len(word) == userLength:
words.append(word)
input() returns a string py3.x , so you must convert it to int first.
userLength = int(input ("Please tell us how long word you want to play : "))
And instead of using readlines you can iterate over one line at once, it is memory efficient. Secondly use the with statement when handling files as it automatically closes the file for you.:
with open("test.txt") as f:
for line in f: #fetches a single line each time
line = line.strip() #remove newline or other whitespace charcters
wl = len(line)
print (wl)
if wl == userLength:
words = line
print (words)

Categories