I'm currently working on a code to translate lines of text into a variation of pig latin,
and one of the requirements is that at any occurrence of a double consonant (bb, cc, dd, etc.)
the string needs to split between those two consonants and reform the word to look like:
"s" + part 2 + part 1 + "s".
The first part of my code is
raw = input("Enter a line to be translated: ")
words = raw.split()
for word in words:
Any help would be greatly appreciated.
Example input/output: "hello, I am Sammy, nice to meet you" = "slohels, I am smysams, nice to meet you"
You might want to use regular expression here...
>>> import re
>>> s = 'hello, I am Sammy, nice to meet you'
>>> re.sub('((\w*([bcdfghjklmnpqrstvwxyz]))(\\3\w*))', 's\\4\\2s', s)
'slohels, I am smySams, nice to meet you'
Almost there... :)
I'll help you on the way a bit.
double_consonants = [2*c for c in 'bcdfghjklmnpqrstvwxz']
for word in raw:
for d_c in double_consonants:
if d_c in word:
# You should be able to finish this bit yourself
You should have a look at the string methods. Tip: Try:
>> s = "I am going to apply for a job".split('pp')
What does that return? Another tip is to use something like the code above, and place it inside a for loop. Maybe you should split the springs into a list of words first?
Edit: The reason I don't give you the entire answer here, is that I suspect that this is a homework assignment.
Related
For instance, if the user entered "Hello welcome to the code" and the program was looking for the character 'e' the program would print:
Hello
welcome
the
code
This looks like a honework assignment ... if thats the case, please keep in mind that if u dont understand the basics and u dont try to understand it, you will never learn it ... also, SO is here to help u with your problem, when u get stuck by getting somekinda error or something ... right now all u did is nothing and u r just crying for help ... but I have a good more, so here is the code that does it (u should know how to ha dle input ;))
inp = "Bla bla bla bla tra tra tea"
inp2 = "r"
words = inp.split(" ")
for w in words:
if inp2 in w:
print(w)
Also u need to fix formatting (this eill print each word to a different line ;) ... if u have any other questions, please let me know :)
It seems like you want to print all words that contain a specific letter. Just split the string on the spaces then either remove all the words that don't have the char or add those that do to a new list then join the list on a space to recombine it. This approach does assume there is are spaces between each word not tabs or newlines (you can just remove the ' ' from the split to split on whitespace but this approach always reassembles the good words using single spaces.
words = line.split(' ')
goodWords = []
for word in words:
if word.find(keyChar) != -1:
goodWords.append(word)
goodLine = ' '.join(goodWords)
Just use the .split function, it will split each individual word up into an array list so that you can individually assess each word.
This question already has answers here:
How to strip all whitespace from string
(14 answers)
Closed 4 years ago.
Basically, I'm trying to do a code in Python where a user inputs a sentence. However, I need my code to remove ALL whitespaces (e.g. tabs, space, index, etc.) and print it out.
This is what I have so far:
def output_without_whitespace(text):
newText = text.split("")
print('String with no whitespaces: '.join(newText))
I'm clear that I'm doing a lot wrong here and I'm missing plenty, but, I haven't been able to thoroughly go over splitting and joining strings yet, so it'd be great if someone explained it to me.
This is the whole code that I have so far:
text = input(str('Enter a sentence: '))
print(f'You entered: {text}')
def get_num_of_characters(text):
result = 0
for char in text:
result += 1
return result
print('Number of characters: ', get_num_of_characters(text))
def output_without_whitespace(text):
newtext = "".join(text.split())
print(f'String without whitespaces: {newtext}')
I FIGURED OUT MY PROBLEM!
I realize that in this line of code.
print(f'String without whitespaces: {newtext}')
It's supposed to be.
print('String without whitespaces: ', output_without_whitespace(text))
I realize that my problem as to why the sentence without whitespaces was not printing back out to me was, because I was not calling out my function!
You have the right idea, but here's how to implement it with split and join:
def output_without_whitespace(text):
return ''.join(text.split())
so that:
output_without_whitespace(' this\t is a\n test..\n ')
would return:
thisisatest..
A trivial solution is to just use split and rejoin (similar to what you are doing):
def output_without_whitespace(text):
return ''.join(text.split())
First we split the initial string to a list of words, then we join them all together.
So to think about it a bit:
text.split()
will give us a list of words (split by any whitespace). So for example:
'hello world'.split() -> ['hello', 'world']
And finally
''.join(<result of text.split()>)
joins all of the words in the given list to a single string. So:
''.join(['hello', 'world']) -> 'helloworld'
See Remove all whitespace in a string in Python for more ways to do it.
Get input, split, join
s = ''.join((input('Enter string: ').split()))
Enter string: vash the stampede
vashthestampede
There are a few different ways to do this, but this seems the most obvious one to me. It is simple and efficient.
>>> with_spaces = ' The quick brown fox '
>>> list_no_spaces = with_spaces.split()
>>> ''.join(list_no_spaces)
'Thequickbrownfox'
.split() with no parameter splits a string into a list wherever there's one or more white space characters, leaving out the white space...more details here.
''.join(list_no_spaces) joins elements of the list into a string with nothing betwen the elements, which is what you want here: 'Thequickbrownfox'.
If you had used ','.join(list_no_spaces) you'd get 'The,quick,brown,fox'.
Experienced Python programmers tend to use regular expressions sparingly. Often it's better to use tools like .split() and .join() to do the work, and keep regular expressions for where there is no alternative.
I want to split a sentence based upon words currently stored in an array. The array stores the words that I want to act as a split point. Can I use an array as split point using regex?
Example:
array=['and','also','but']
Text file:
I am new to Python and I need help. I am also asking a question.
Required output:
I need help
asking a question
You can use re.split() function:
import re
array = ['and','also','but']
sentence = "I am new to Python and I need help. I am also asking a question."
result = re.split("|".join(array), sentence)
I will add a trim:
result = [x.strip() for x in result]
print(result)
Here's an adaptation of #hurturk solution - that will produce #blahhh requested output.
Since my crystal ball broke last week, whether this algorithm is what #blahhh intended, is anyone's guess.
from __future__ import print_function
import re
array = ['and', 'also', 'but']
separators = ['\.', '\;', '\?', '\!']
sentence = "I am new to Python and I need help. I am also asking a question."
sentences = re.split("|".join(separators), sentence)
for sentence in sentences:
result = re.split("|".join(array), sentence)
result = [x.strip() for x in result]
print(result[-1])
where the output is:
I need help
asking a question
I'm learning Python and have been taking an online class. This class was very basic and I am know trying to continue my studies elsewhere. Stackoverflow.com has helped me a great deal. In the online course we didn't cover a lot about return statements, which I am now trying to learn. I would like to do something very basic, so I was thinking of creating a program that would receive a string as an argument without having any return value. I want the user to type a word that will be shown with characters or symbols between every letter.
Example
User types in the word Python.
The word will be shown as =P=y=t=h=o=n= or -P-y-t-h-o-n- or maybe with * between every letter.
Is this an easy task? Can someone help me how to go about doing this?
Thank you.
Joel
If you want to do it yourself, you can go through your string like this:
my_string = "Python"
for letter in my_string:
# do something with the letter
print(letter)
This will print each letter in your word. What you want to do is having a new string with your desired character. You probably know you can concatenate (append) two strings in this way :
str1 = "hello"
str2 = "world"
str3 = str1 + str2
print(str3) #helloworld
So to do what you'd like to do, you can see each letter as a substring of your main string, and your desired character (for example *) as another string, and build a result string in that way.
inputString = "Python"
result = ""
myChar = "*"
for letter in inputString:
# build your result
build = build + letter
print(build)
This will just copy inputString into result, though I think you'll have understood how to use it in order to add your custom chars between the letters.
Yes python makes this sort of string manipulation very easy (some other languages... not so much). Look up the standard join function in the python docs.
def fancy_print(s, join_char='-'):
# split string into a list of characters
letters = list(s)
# create joined string
output = join_char + join_char.join(letters) + join_char
# show it
print(output)
then
>>> fancy_print("PYTHON")
-P-Y-T-H-O-N-
>>> fancy_print("PYTHON", "*")
*P*Y*T*H*O*N*
So I've been learning Python for some months now and was wondering how I would go about writing a function that will count the number of times a word occurs in a sentence. I would appreciate if someone could please give me a step-by-step method for doing this.
Quick answer:
def count_occurrences(word, sentence):
return sentence.lower().split().count(word)
'some string.split() will split the string on whitespace (spaces, tabs and linefeeds) into a list of word-ish things. Then ['some', 'string'].count(item) returns the number of times item occurs in the list.
That doesn't handle removing punctuation. You could do that using string.maketrans and str.translate.
# Make collection of chars to keep (don't translate them)
import string
keep = string.lowercase + string.digits + string.whitespace
table = string.maketrans(keep, keep)
delete = ''.join(set(string.printable) - set(keep))
def count_occurrences(word, sentence):
return sentence.lower().translate(table, delete).split().count(word)
The key here is that we've constructed the string delete so that it contains all the ascii characters except letters, numbers and spaces. Then str.translate in this case takes a translation table that doesn't change the string, but also a string of chars to strip out.
wilberforce has the quick, correct answer, and I'll give the long winded 'how to get to that conclusion' answer.
First, here are some tools to get you started, and some questions you need to ask yourself.
You need to read the section on Sequence Types, in the python docs, because it is your best friend for solving this problem. Seriously, read it. Once you have read that, you should have some ideas. For example you can take a long string and break it up using the split() function. To be explicit:
mystring = "This sentence is a simple sentence."
result = mystring.split()
print result
print "The total number of words is: " + str(len(result))
print "The word 'sentence' occurs: " + str(result.count("sentence"))
Takes the input string and splits it on any whitespace, and will give you:
["This", "sentence", "is", "a", "simple", "sentence."]
The total number of words is 6
The word 'sentence' occurs: 1
Now note here that you do have the period still at the end of the second 'sentence'. This is a problem because 'sentence' is not the same as 'sentence.'. If you are going to go over your list and count words, you need to make sure that the strings are identical. You may need to find and remove some punctuation.
A naieve approach to this might be:
no_period_string = mystring.replace(".", " ")
print no_period_string
To get me a period-less sentence:
"This sentence is a simple sentence"
You also need to decide if your input going to be just a single sentence, or maybe a paragraph of text. If you have many sentences in your input, you might want to find a way to break them up into individual sentences, and find the periods (or question marks, or exclamation marks, or other punctuation that ends a sentence). Once you find out where in the string the 'sentence terminator' is you could maybe split up the string at that point, or something like that.
You should give this a try yourself - hopefully I've peppered in enough hints to get you to look at some specific functions in the documentation.
Simplest way:
def count_occurrences(word, sentence):
return sentence.count(word)
text=input("Enter your sentence:")
print("'the' appears", text.count("the"),"times")
simplest way to do it
Problem with using count() method is that it not always gives the correct number of occurrence when there is overlapping, for example
print('banana'.count('ana'))
output
1
but 'ana' occurs twice in 'banana'
To solve this issue, i used
def total_occurrence(string,word):
count = 0
tempsting = string
while(word in tempsting):
count +=1
tempsting = tempsting[tempsting.index(word)+1:]
return count
You can do it like this:
def countWord(word):
numWord = 0
for i in range(1, len(word)-1):
if word[i-1:i+3] == 'word':
numWord += 1
print 'Number of times "word" occurs is:', numWord
then calling the string:
countWord('wordetcetcetcetcetcetcetcword')
will return: Number of times "word" occurs is: 2
def check_Search_WordCount(mySearchStr, mySentence):
len_mySentence = len(mySentence)
len_Sentence_without_Find_Word = len(mySentence.replace(mySearchStr,""))
len_Remaining_Sentence = len_mySentence - len_Sentence_without_Find_Word
count = len_Remaining_Sentence/len(mySearchStr)
return (int(count))
I assume that you just know about python string and for loop.
def count_occurences(s,word):
count = 0
for i in range(len(s)):
if s[i:i+len(word)] == word:
count += 1
return count
mystring = "This sentence is a simple sentence."
myword = "sentence"
print(count_occurences(mystring,myword))
explanation:
s[i:i+len(word)]: slicing the string s to extract a word having the same length with the word (argument)
count += 1 : increase the counter whenever matched.