Count on which loop text was entered and display as index - python-3.x

I'm working on a small program which takes a text input - and then places each of these items in a dictionary alongside which line they were entered on. At the moment if I enter 4 lines of text. It'll take them all out correctly, but every word will be set to the value 4 - instead of the loop it was inputted on. I've removed all the other functions from my code (remove punct, remove stopwords, stemwords, etc). to make this clearer.
from string import *
function = False
words_split = []
lineNumber=0
final_value = []
def indexer(t):
global words_split
words = t.split();
for word in words:
words_split.append(word)
def dict_print():
for keys in Dict:
output = keys + " " + str(Dict[keys][0])
i= 1
while i < len(Dict[keys]):
output = output + ", " + str(Dict[keys][i])
i = i + 1
print(output)
print("Please type a line and hit 'Enter' or type a single fullstop followed by 'Enter' to exit \n")
text = ""
while function == False :
if(text == "."):
print("The index is:")
function = True
dict_print()
else:
Dict = {}
text = input()
lineNumber += 1
for word in words_split:
if word in Dict:
if lineNumber not in Dict[word]:
Dict[word] = Dict[word] + [lineNumber]
else:
Dict[word] = [lineNumber]
indexer(text)

My global variable was causing the issue. I'll leave this up with my completed full code in case someone else runs into the same issue (:
https://repl.it/#Glaschu/AdmiredSteelCardinal

Related

URL Encoding using a loop

I am trying to use the following function to return the string with every space replaced with a %20. However, it only prints out the '%20' in each of the print statement outputs. I am also trying to omit replacing the first space in a string. Any ideas? I know that there is library and a .replace() method that exits to solve this, but I want to use a for loop and conditionals.
def urlEncode(text):
result = ''
for i in text:
if i == ' ':
i = '%20'
result = result + i
return result
print(urlEncode("Lighthouse Labs"))
print(urlEncode(" Lighthouse Labs "))
print(urlEncode("blue is greener than purple for sure"))
output is:
%20
%20%20%20%20
%20%20%20%20%20%20
Hey you need to add the characters that are not space too, right? Have a look in the edited script.
def urlEncode(text):
result = ''
for i in text:
if i == ' ':
i = '%20'
result += i
else:
result += i
return result
print(urlEncode("Lighthouse Labs"))
print(urlEncode(" Lighthouse Labs "))
print(urlEncode("blue is greener than purple for sure"))
Edit, additional answer: -how to omit first space
def urlEncode(text):
result = ''
counter = 0
for i in text:
if(counter == 0 and text[counter] == ' '):
result += i
elif i == ' ':
i = '%20'
result += i
else:
result += i
counter += 1
return result

Concatenating string outputs of a for loop in Python 3

I have a code which, after a nested for loop, provides me with a unique string in each iteration. I want to find a way to concatenate those outputs so that my final line is a single string of those unique strings. Ignoring how ugly and inefficient this code is, what steps can I take to achieve the desired result?
VOWELS = ('a','e','i','o','u','A','E','I','O','U')
ad = "Desirable unfurnished flat in quiet residential area"
# remove all vowels, unless the word starts with a vowel
def is_vowel(c):
return c in VOWELS
def mod3(ad):
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
print(modAd)
mod3(ad)
my output for this code:
Otherwise, when I modify my code to look like this:
But my output is:
I don't believe a .join() would work here as it's not a list type. And I can't figure out where to put a string concat + anywhere without my for loop going bonkers. Any advice?
You can create a string result where you can concatenate your each iteration result and print that. You need to add spaces after each addition of words. So, append + " " to your result variable as well.
def mod3(ad):
result = ""
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
result += modAd + " "
print(result)
Second option: This is my take on it:
def mod4(ad):
result = ""
testAd =ad.split()
for word in testAd:
for i, char in enumerate(word):
if i == 0:
result += char
if i > 0 and char not in VOWELS:
result += char
result += " "
print(result)

Problem with Python Code and the Functions in it

I have a Problem, I have to solve a task in Python and I dont know how to do it. The task is to define a function number_of_vowels, where the output should be the Number of vowels in a Word. With this function I have to write anotherone, many_vowels thats working with a list an a Number and where the number says how many vowels have to be at least in a word to be appended to the result list and then I have to append this Word. Thanks to everybody helping me ;D.
here is the code:
Wort = "parameter"
def number_of_vowels(Word):
result = 0
counter0 = 0
while result < 20:
if Word[counter0] == 'a' or 'e' or 'i' or 'o' or 'u':
result = result + 1
counter0 = counter0 + 1
else:
counter0 = counter0 + 1
return result
Words = []
counter1 = 0
def many_vowels(List , number):
if number_of_vowels(List[counter1]) < number:
counter1 + 1
else:
Words.append(List[counter1])
counter1 + 1
return Words
This code just gives me the answer to the letter a and not to the other vowels. For
print(number_of_vowels(Wort))
the output is: 1
but there are 4 vowels in this word
it also says: line 21, in many_vowels
IndexError: string index out of range
You're trying to call a function with wrong brackets. Function call should use round ones.
Try changing number_of_vowels[List[counter1]] with number_of_vowels(List[counter1])
This code contains some errors:
Calling for function should be using round brackets: number_of_vowels(List[counter1]) instead of number_of_vowels[List[counter1]]
doing result + 1 won't change value of the variable result, since you did not put the calculation result in the variable. use result = result + 1 (same for counters)
in number_of_vowels function, you want to scan the whole word? cause you did not use any loop, so it currently looking only at the first letter. Secondly, you put the compression in result and then add 1 to it. I'm not really sure why
edit:
Word = "parameter"
def number_of_vowels(Word):
result = 0
counter0 = 0
for index, letter in enumerate(Word):
if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
result = result + 1
return result
Words = []
counter1 = 0
def many_vowels(List_name , number):
for index, item in enumerate (List_name):
if number_of_vowels(item) >= number:
Words.append(item)
return Words

String index out of range, Python

code for a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number the number 1 should be appended to the new string.
The output is correct but it is showing a String index out of range error. Can someone help me on where and how the string index is out of range?
test cases,expected output:
(increment_string("foo"), "foo1"),(increment_string("foobar001"), "foobar002"),(increment_string("foobar1"), "foobar2"),(increment_string("foobar00"), "foobar01"),("foobar99"), "foobar100"),("foobar099"), "foobar100"),(increment_string(""), "1")
def increment_string(strng):
if strng[-1].isdigit():
exp_strng=strng[::-1]
new_strng=""
new_strng1=""
for i in exp_strng:
if i.isdigit():
new_strng+=i
else:
break
new_strng=new_strng[::-1]
new_strng1=int(new_strng)+1
new_strng1='{num:{fill}{width}}'.format(num=new_strng1, fill='0', width=len(new_strng))
return(strng[:-len(new_strng)]+new_strng1)
else:
strng+="1"
return(strng)
Since you gave us more information on the test cases given, you can bypass the edge case of an empty string by modifying the if statement:
def increment_string(strng):
# Add it here #
if strng == "":
return "1"
elif strng[-1].isdigit():
exp_strng = strng[::-1]
new_strng = ""
new_strng1 = ""
for i in exp_strng:
if i.isdigit():
new_strng += i
else:
break
new_strng = new_strng[::-1]
new_strng1 = int(new_strng) + 1
new_strng1 = '{num:{fill}{width}}'.format(num=new_strng1, fill='0', width=len(new_strng))
return strng[:-len(new_strng)] + new_strng1
else:
strng += "1"
return strng
If think this would be a better solution to your problem:
from re import search
def increment_string(s):
number = search('\d+$', s)
if number != None:
number = number.group()
first_part = s.split(number)[0]
return first_part + str(int(number)+1)
else:
return s + '1'
I don't know what you want when the number is 9 though: 0 or 10. This code produces 10.
the error was caused when empty string is passed. and I resolved it by adding one more if else:(thanks to Skam)
def increment_string(strng):
if len(strng)>0:
if strng[-1].isdigit():
exp_strng=strng[::-1]
new_strng=""
new_strng=""
for i in exp_strng:
if i.isdigit():
new_strng+=i
else:
break
new_strng=new_strng[::-1]
new_strng1=int(new_strng)+1
new_strng1=str(new_strng1)
new_strng1=new_strng1.zfill(len(new_strng))
return(strng[:-len(new_strng)]+new_strng1)
else:
strng+="1"
return(strng)
else:
strng+="1"
return(strng)

pig latin issues with output code for python

I am having trouble with the code only producing the first two letters of the first word and then attaching the 'AY' to the end while it runs. I can't seem to figure out how to correct this error.
def main():
strin = input('Enter a sentence (English): ')
strlist = strin.split()
i = 0
pigsen = ''
while i < len(strlist):
word = strlist[i]
j = 1
fc = word[0].upper()
pigword =''
while j < len(word):
pigword += word[j].upper()
j += 1
pigword += fc + 'AY'
pigsen += pigword + ' '
i +=1
print('Pig Latin: ' +str(pigsen))
main()
First, I'll assume this is just the start of a pig Latin generator and you'll add the other rules (at least a couple more) once you get this much working. Second, let's simplify the code as a way of fixing it:
def main():
sentence = input('Enter a sentence (English): ')
words = sentence.upper().split()
latin_words = []
for word in words:
first, rest = word[0], word[1:]
latin_word = rest + first + 'AY'
latin_words.append(latin_word)
print('Pig Latin:', *latin_words)
main()
USAGE
> python3 test.py
Enter a sentence (English): He complimented me on my English
Pig Latin: EHAY OMPLIMENTEDCAY EMAY NOAY YMAY NGLISHEAY
>
I would say the problem with your code is you made it too complicated.

Resources