Invalid Syntax because of commas - python-3.x

I was trying to do a program that counts vowels, consonants and other chars. The problem is in the returning because of commas and I can't understand why. It is supposed to return, for example, "2 vowels, 3 consonants and 5 others".
This is my program (sorry for any english mistakes):
def count1(word):
vowels = 0
consonants = 0
others = 0
l1 = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']
for i in range(len(word)):
if word[i] in l1:
vowels = vowels + 1
elif (word[i] >= 'a' and word[i] <= 'z') or (word[i] >=
'A' and word[i] <= 'Z'):
consonants = consonants + 1
else :
others = others+ 1
return(vowels "vowels," consonants "consonants," outros "others")

You should format the string before you return it:
return '{} vowels, {} consonants, {} others'.format(vowels, consonants, others)
Or using f-string in Python 3.6+
return f'{vowels} vowels, {consonants} consonants, {others} others'

Related

Problems with Randomized Guessing Game

this is my first post here so bear with me. I decided to take an online coding course to help me learn the basics of Python, up until now it's been great. Difficult, but manageable. Well, it appears I've hit a wall. I am trying to write a program that randomly generates a word from a wordlist.txt file then allow the user to guess letters in said word with a set amount of guesses.
'''
import random
def pick_word_from_file():
file = open("wordlist.txt", 'r')
words = file.readlines()
file.close()
word = random.choice(words).strip("\n")
return word
word = pick_word_from_file()
hidden_word = len(word)
num_of_guesses = 5
print('Welcome to Guess a Letter!')
print('Your word has {} letters.'.format(hidden_word))
print('You have {} guesses left!'.format(num_of_guesses))
new_word = []
for i in range(hidden_word):
new_word.append('_')
print(new_word)
while num_of_guesses > 0:
guess = input('Take a guess!')
if guess in word:
num_of_guesses = num_of_guesses - 1
pass
else:
num_of_guesses = num_of_guesses - 1
print('Oof! looks like that letter is not in the word!')
if num_of_guesses == 0:
Print('All out of guesses!')
'''
What I am currently struggling with is replacing the hashed out letter of the randomized word with the correct guess. Every time is a guess is correct it should output that letter in the correct space for the word.
My approach to this problem is storing the indices of each character in a dictionary like this.
>>> word = 'python'
>>> word_loc = {}
>>> for idx, char in enumerate(word):
... word_loc[char] = word_loc.get(char, []) + [idx]
...
>>> word_loc
{'p': [0], 'y': [1], 't': [2], 'h': [3], 'o': [4], 'n': [5]}
Next, update each index accordingly when the guess is correct.
>>> while True:
... guess = input('Take a guess!\n')
... if len(guess) != 1:
... print('Invalid guess!')
... elif guess in word:
... print('correct guess!')
... for idx in word_loc[guess]:
... new_word[idx] = guess
... print(new_word)
... if ''.join(new_word) == word:
... print('Congratulations! You've guessed the word correctly!')
... break
... else:
... num_of_guesses -= 1
... print('Incorrect guess! Remaining attempts = {}'.format(num_of_guesses))
... if num_of_guesses == 0:
... print('You failed to guess the word! Aborting program!')
... break
...
Take a guess!
s
Incorrect guess! Remaining attempts = 4
Take a guess!
r
Incorrect guess! Remaining attempts = 3
Take a guess!
p
correct guess!
['p', '_', '_', '_', '_', '_']
Take a guess!
y
correct guess!
['p', 'y', '_', '_', '_', '_']
Take a guess!
c
Incorrect guess! Remaining attempts = 2
Take a guess!
h
correct guess!
['p', 'y', '_', 'h', '_', '_']
Take a guess!
n
correct guess!
['p', 'y', '_', 'h', '_', 'n']
Take a guess!
s
Incorrect guess! Remaining attempts = 1
Take a guess!
a
Incorrect guess! Remaining attempts = 0
You failed to guess the word! Aborting program!

Changing utf-8 string to cp1251 (Python)

I'm trying to convert Excel file with polish chars such as "ęśążćółń" to normal letters "esazcoln". Firstly I've menaged to convert xlsx file to txt, then:
f = open("PATH_TO_TXT_FILE")
r = f.read()
r.upper()
new_word = ""
for char in r:
if char == "Ą":
new_word += "A"
elif char == "Ć":
new_word += "C"
elif char == "Ę":
new_word += "E"
elif char == "Ł":
new_word += "L"
elif char == "Ó":
new_word += "O"
elif char == "Ż" "Ź":
new_word += "Z"
elif char == "Ź":
new_word += "Z"
elif char == "Ś":
new_word += "S"
else:
new_word += char
encoded_bytes = r.encode('utf-8', "replace")
decoded = encoded_bytes.decode(
"cp1252", "replace")
print(decoded)
in file is written : asdżółć
Output: asdżółć
I'd like to recive: asdzolc
Is there anybody who can help me?
I can't find the stack overflow page from which I got the pattern/sub template, but this is the general idea:
#!/usr/bin/env python3
# coding: UTF-8
import re
mapping = {
'Ą': 'A',
'Ć': 'C',
'Ę': 'E',
'Ł': 'L',
'Ó': 'O',
'Ż': 'Z',
'Ź': 'Z',
'Ś': 'S',
'ą': 'a',
'ć': 'c',
'ę': 'e',
'ł': 'l',
'ó': 'o',
'ż': 'z',
'ź': 'z',
'ś': 's',
}
pattern = re.compile("|".join(mapping.keys()))
def replace_by_mapping(text):
return pattern.sub(lambda m: mapping[re.escape(m.group(0))], text)
if __name__ == '__main__':
with open('polish_test.txt', 'r') as f:
contents = f.read()
contents = replace_by_mapping(contents)
print(contents)

How to delete the vowel from a given string

How to delete the vowel from the given string?
letter = 'raeiou'
new_string = []
for i in letter:
new_string.append(i)
for j in new_string:
if j == 'a' or j == 'e' or j == 'i' or j == 'o' or j == 'u':
new_string.remove(j)
final = ''.join(new_string)
print('The string after removing the vowels is {}'.format(final))
expected output r but reo
When you do:
for j in new_string:
...
new_string.remove(...)
you are modifying a list while looping on it (see e.g. strange result when removing item from a list).
You could simply skip vowels when you create new_list in the first place:
for i in letter:
if not i in 'aeiou':
new_string.append(i)
final = ''.join(new_string)
Here is an alternative suggestion:
def func(s):
for c in 'aeiouAEIOU':
s = ''.join(s.split(c))
return s
You don't need two loops for this!
letter = 'raeiou'
new_string = letter
vowels = ('a', 'e', 'i', 'o', 'u')
for i in letter:
if i in vowels:
new_string = new_string.replace(i,"");
print('The string after removing the vowels is {}'.format(new_string))

Pig Latin Program in Python

Write a program in Python 3 that converts a sentence typed in by the user to Pig Latin. Pig Latin has two rules:
If a word begins with a consonant all consonants before the first
vowel are moved to the end of the word and the letters "ay" are then
added to the end. e.g. "coin" becomes "oincay" and "flute" becomes
"uteflay". If a word begins with a vowel then "yay" is added to the
end. e.g."egg" becomes "eggyay" and "oak" becomes "oakyay".
My code works for individual words but does not work for sentence. I have tried entering:
wordList = word.lower().split(" ")
for word in wordList:
but it does not work.
#Pig Latin Program
import sys
VOWELS = ('a', 'e', 'i', 'o', 'u')
def pig_latin(word):
if (word[0] in VOWELS):
return (word +"yay")
else:
for letter in word:
if letter in VOWELS:
return (word[word.index(letter):] + word[:word.index(letter)] + "ay")
return word
word = ""
while True:
word = input("Type in the word or Exit to exit:")
if (word == "exit" or word == "Exit" or word == "EXIT"):
print("Goodbye")
sys.exit()
else:
print(pig_latin(word))
The input sentence: the rain in Spain
The output sentence: ethay ainray inyay ainSpay
So you could do something like this, it returns an iterable of all the pig-ed words and you can join them in the last step. You don't need that last return you have. My guess is the issue you saw was that you are returning in the first loop. you could track the return outside the loop and append to it in the loop and return that also.
import sys
VOWELS = ('a', 'e', 'i', 'o', 'u')
def pig_latin(word):
wordList = word.lower().split(" ")
for word in wordList:
if (word[0] in VOWELS):
yield (word +"yay")
else:
for letter in word:
if letter in VOWELS:
yield (word[word.index(letter):] + word[:word.index(letter)]+ "ay")
break
word = ""
while True:
word = input("Type in the word or Exit to exit:")
if (word == "exit" or word == "Exit" or word == "EXIT"):
print("Goodbye")
sys.exit()
else:
print(' '.join(pig_latin(word)))

My for loop is not iterating through all possible values

I'm trying to store substrings of letters in 's' that are in alphabetical order in a list
s = 'azcbobobegghakl'
string = ''
List = []
i = -1
for letter in s:
if letter == s[0]:
string += letter
elif letter >= s[i]:
string += letter
elif letter < s[i]:
List.append(string)
string = letter
i += 1
print(List)
My expected result:
['az', 'c', 'bo', 'bo', 'beggh', 'akl']
And my actual Output:
['az', 'c', 'bo', 'bo']
Firstly, your first if statement is incorrect. It should be if i == -1:. Because of this bug, you are ignoring the second a character in s.
Secondly, at the end of the string you don't add what's left of string into List.
As such, the following is what you want:
s = 'azcbobobegghakl'
string = ''
List = []
i = -1
for letter in s:
if i == -1:
string += letter
elif letter >= s[i]:
string += letter
elif letter < s[i]:
List.append(string)
string = letter
i += 1
List.append(string)
print(List)
An example is available here.

Resources