Removing Spaces in Python not working - python

I am trying to remove spaces.
I have tried everything from previous threads including re.sub
Code:
wordinput = (input("Input:\n"))
wordinput = wordinput.lower()
cleanword = wordinput.replace(" ","")
cleanword = wordinput.replace(",","")
cleanword = wordinput.replace(".","")
revword = cleanword [::-1]
print(cleanword)
print(revword)
print("Output:")
if (cleanword == revword):
print('"The word ' + wordinput + ' is a palindrome!"')
else:
print('"Unfortunately the word ' + wordinput + ' is not a palindrome. :(')
Output:
Input:
mr owl ate my metal worm
mr owl ate my metal worm
mrow latem ym eta lwo rm
Output:
"Unfortunately the word mr owl ate my metal worm is not a palindrome. :(

The problem you are having is here:
cleanword = wordinput.replace(" ","")
cleanword = wordinput.replace(",","")
cleanword = wordinput.replace(".","")
You are not saving the results of the previous replace.
Try:
cleanword = wordinput.replace(" ", "").replace(",", "").replace(".", "")

#StephenRauch explains your problem well.
But here is a better way to implement your logic:
chars = ',. '
wordinput = 'mr owl ate my metal worm '
cleanword = wordinput.translate(dict.fromkeys(map(ord, chars)))
# 'mrowlatemymetalworm'

Did you try something like:
import re
cleanword = re.sub(r'\W+', '', wordinput.lower())

wordinput = (input("Input:\n"))
cleanword=''.join([e for e in wordinput.lower() if e not in ", ."])
You could try this comprehension

Maybe you should try this one:
wordinput = raw_input("Input:\n")
cleanword =''.join([x for x in wordinput.lower() if x not in (',','.',' ')])
if cleanword[:] == cleanword[::-1]:
print ('"The word ' + wordinput + ' is a palindrome!"')
else:
print ('"The word ' + wordinput + ' is not a palindrome!"')

After first replace, on subsequent replace, you need to use cleanword which is the updated string instead of wordinput. You can try following:
wordinput = (input("Input:\n"))
wordinput = wordinput.lower()
cleanword = wordinput.replace(" ","")
# updating 'cleanword' and saving it
cleanword = cleanword.replace(",","")
cleanword = cleanword.replace(".","")
revword = cleanword [::-1]
print(cleanword)
print(revword)
print("Output:")
if (cleanword == revword):
print('"The word ' + wordinput + ' is a palindrome!"')
else:
print('"Unfortunately the word ' + wordinput + ' is not a palindrome. :(')

Related

Line split is not functioning as intended

I am trying to get this code to split one at a time, but it is not functioning as expected:
for line in text_line:
one_line = line.split(' ',1)
if len(one_line) > 1:
acro = one_line[0].strip()
meaning = one_line[1].strip()
if acro in acronyms_dict:
acronyms_dict[acro] = acronyms_dict[acro] + ', ' + meaning
else:
acronyms_dict[acro] = meaning
Remove the ' ' from the str.split. The file is using tabs to delimit the acronyms:
import requests
data_site = requests.get(
"https://raw.githubusercontent.com/priscian/nlp/master/OpenNLP/models/coref/acronyms.txt"
)
text_line = data_site.text.split("\n")
acronyms_dict = {}
for line in text_line:
one_line = line.split(maxsplit=1) # <-- remove the ' '
if len(one_line) > 1:
acro = one_line[0].strip()
meaning = one_line[1].strip()
if acro in acronyms_dict:
acronyms_dict[acro] = acronyms_dict[acro] + ", " + meaning
else:
acronyms_dict[acro] = meaning
print(acronyms_dict)
Prints:
{
'24KHGE': '24 Karat Heavy Gold Electroplate',
'2B1Q': '2 Binary 1 Quaternary',
'2D': '2-Dimensional',
...

Why does my python script works in IDLE and when executed from CMD but not from double clicking

I'm struggling to debug this but I'm afraid it's beyond my current understanding.
I created a simple script in python which purpose in life is to take as input a string (copy-pasted from google sheets) and turn it into a csv file that will be fit to upload to google calendar. It's hard-coded to fit the format of our shift plan at work. Suffice to say that exemplary input could be: MSLS-1Comp-offES-1..ES-22. The program then parses the input according to specified rules, prints parsed items as list and finally creates a csv file in a correct format.
Here is the problem:
The program runs perfectly everywhere I try it, except when I try running it by double clicking it on the desktop (Windows10). When running from CMD, IDLE or online, the program works and produces expected results without any errors. Other simple scripts I wrote, run from the desktop no problem. In this particular one, the program opens (as all the others, in python3.9), but at a particular line just exits (again, it doesn't happen when I run this program from the cmd, IDLE or online). I managed to find the place where the program 'crashes' by inserting print functions. It looks to me that for some reason the program exits/crashes on the line with io.open("shifts.csv", "w", encoding="utf-8-sig") as f:.
Is it something with the code? Then why does it run ok when run on the same system just using the command prompt? Is it something with how I have python set up on my computer? In which case why do others scripts I wrote run perfectly from the desktop? I'm really confused here. I would be very grateful for any suggestions. Thank you!
Here is the full code:
import subprocess
import sys
import io
year = "2021"
month = input("Please enter month in number format (e.g., '07' for June):\n")
shifts = input("Please paste your shifts:\n")
word = ''
shifts_list = []
for char in shifts: # iterate through the string
word = word + char # add the character to the word
if(char in ['1','2','3','.']): # check if the character at current iteration is one of the characters in the list
shifts_list.append(word) # add the word formed by now to the list
word = '' # re-initialize the word variable to an empty string so as to start the next word
if (char in ['S'] and word[-2] in ['M']):
shifts_list.append(word) # add the word formed by now to the list
word = '' # re-initialize the word variable to an empty string so as to start the next word
print(shifts_list)
headers = "Subject, Start Date, Start Time, End Date, End Time, Description, Private\n"
start_times = ["6:30", "7:30", "6:30", "9:00", "10:00"]
end_times = ["15:00", "16:00", "17:00", "17:30", "18:30"]
subjects = ["Early 🌼", "Office 👔", "10h 👷", "Middle 🌻", "Late 🦉"]
print(headers)
input("after this point the program exits")
with io.open("shifts.csv", "w", encoding="utf-8-sig") as f:
f.write(headers)
for day, shift in enumerate(shifts_list):
description = shift
date = str(day+1) + "." + month + "." + year
if shift == "Int-ES1":
print(subjects[0] + ', ' + date +', ' + start_times[0] + ', ' + date + ', ' + end_times[0] + ', ' + description + ', ' + "TRUE\n")
f.write(subjects[0] + ', ' + date +', ' + start_times[0] + ', ' + date + ', ' + end_times[0] + ', ' + description + ', ' + "TRUE\n")
if shift == "Int-ES2":
print(subjects[1] + ', ' + date +', ' + start_times[1] + ', ' + date + ', ' + end_times[1] + ', ' + description + ', ' + "TRUE\n")
f.write(subjects[1] + ', ' + date +', ' + start_times[1] + ', ' + date + ', ' + end_times[1] + ', ' + description + ', ' + "TRUE\n")
if shift == "IntES3":
print(subjects[2] + ', ' + date +', ' + start_times[2] + ', ' + date + ', ' + end_times[2] + ', ' + description + ', ' + "TRUE\n")
f.write(subjects[2] + ', ' + date +', ' + start_times[2] + ', ' + date + ', ' + end_times[2] + ', ' + description + ', ' + "TRUE\n")
if shift == "MS":
print(subjects[3] + ', ' + date +', ' + start_times[3] + ', ' + date + ', ' + end_times[3] + ', ' + description + ', ' + "TRUE\n")
f.write(subjects[3] + ', ' + date +', ' + start_times[3] + ', ' + date + ', ' + end_times[3] + ', ' + description + ', ' + "TRUE\n")
if shift == "Int-LS1":
print(subjects[4] + ', ' + date +', ' + start_times[4] + ', ' + date + ', ' + end_times[4] + ', ' + description + ', ' + "TRUE\n")
f.write(subjects[4] + ', ' + date +', ' + start_times[4] + ', ' + date + ', ' + end_times[4] + ', ' + description + ', ' + "TRUE\n")
print("Your shifts have been successfully saved to a CSV file. You can now import it to your calendar :)")
input("Press enter to exit...")
def open_folder(path):
if sys.platform == 'darwin':
subprocess.check_call(['open', '--', path])
elif sys.platform == 'linux2':
subprocess.check_call(['gnome-open', '--', path])
elif sys.platform == 'win64':
subprocess.check_call(['explorer', path])
open_folder(path=".") # open current directory

Why polyglot does not return the un-transliterated text back?

eg = 'bajra bechna बाजरा बेचना'
fin=''
text = Text(eg)
for x in text.transliterate("en"):
fin = fin + ' ' + str(x)
print(fin)
output:
बाजरा बेचना
I am loosing the initial English text in the output. How can I get all of it in the output?

How to add a space in hangman game

I'm trying to make a game, where a song name is picked from a file, and the title is replaced with underscores (apart from the first letter)
However I'm not sure how to add a space into it, as some songs are more than one word, this is what I have currently:
def QuizStart():
line = random.choice(open('songnamefile.txt').readlines())
line.split('-')
songname, artist = line.split('-')
underscoresong = songname
i=0
song_name = range(1,len(songname))
for i in song_name:
if ' ' in song_name:
i=i+1
else:
underscoresong = underscoresong.replace(songname[i],"_")
i=i+1
print(underscoresong, ' - ', artist)
It would be good to include expected output for a given input examples.
You can just multiply an array containing the placeholder character n times. e.g.:
songname = 'My blue submarine'
underscoresong = ''.join([songname[0]] + ['_'] * (len(songname) - 1))
print(underscoresong)
Output:
M________________
That will add the first character and then the underscore for as long as the songname is, minus one (for the first character). The join converts it to a string.
Or if you want to preserve spaces:
underscoresong = ''.join(
[songname[0]] + ['_' if c != ' ' else ' ' for c in songname[1:]]
)
print(underscoresong)
Output:
M_ ____ _________
Or if you want to also preserve the single quote:
songname = "God's Plan-Drake"
underscoresong = ''.join(
[songname[0]] +
['_' if c not in {' ', "'"} else c for c in songname[1:]]
)
print(underscoresong)
Output:
G__'_ __________
You could also use regular expressions:
import re
songname = "God's Plan-Drake"
underscoresong = songname[0] + re.sub(r"[^ ']", '_', songname[1:])
print(underscoresong)
Output:
G__'_ __________

Removing words with special characters "\" and "/"

During the analysis of tweets, I run in the "words" that have either \ or / (could have more than one appearance in one "word"). I would like to have such words removed completely but can not quite nail this
This is what I tried:
sen = 'this is \re\store and b\\fre'
sen1 = 'this i\s /re/store and b//fre/'
slash_back = r'(?:[\w_]+\\[\w_]+)'
slash_fwd = r'(?:[\w_]+/+[\w_]+)'
slash_all = r'(?<!\S)[a-z-]+(?=[,.!?:;]?(?!\S))'
strt = re.sub(slash_back,"",sen)
strt1 = re.sub(slash_fwd,"",sen1)
strt2 = re.sub(slash_all,"",sen1)
print strt
print strt1
print strt2
I would like to get:
this is and
this i\s and
this and
However, I receive:
and
this i\s / and /
i\s /re/store b//fre/
To add: in this scenario the "word" is a string separated either by spaces or punctuation signs (like a regular text)
How's this? I added some punctuation examples:
import re
sen = r'this is \re\store and b\\fre'
sen1 = r'this i\s /re/store and b//fre/'
sen2 = r'this is \re\store, and b\\fre!'
sen3 = r'this i\s /re/store, and b//fre/!'
slash_back = r'\s*(?:[\w_]*\\(?:[\w_]*\\)*[\w_]*)'
slash_fwd = r'\s*(?:[\w_]*/(?:[\w_]*/)*[\w_]*)'
slash_all = r'\s*(?:[\w_]*[/\\](?:[\w_]*[/\\])*[\w_]*)'
strt = re.sub(slash_back,"",sen)
strt1 = re.sub(slash_fwd,"",sen1)
strt2 = re.sub(slash_all,"",sen1)
strt3 = re.sub(slash_back,"",sen2)
strt4 = re.sub(slash_fwd,"",sen3)
strt5 = re.sub(slash_all,"",sen3)
print(strt)
print(strt1)
print(strt2)
print(strt3)
print(strt4)
print(strt5)
Output:
this is and
this i\s and
this and
this is, and!
this i\s, and!
this, and!
One way you could do it without re is with join and a comprehension.
sen = 'this is \re\store and b\\fre'
sen1 = 'this i\s /re/store and b//fre/'
remove_back = lambda s: ' '.join(i for i in s.split() if '\\' not in i)
remove_forward = lambda s: ' '.join(i for i in s.split() if '/' not in i)
>>> print(remove_back(sen))
this is and
>>> print(remove_forward(sen1))
this i\s and
>>> print(remove_back(remove_forward(sen1)))
this and

Categories