Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Hello so I have to do a program that identifies all of the positions where a word occurs in a list but when I run my program it doesn't output anything.
Here's my code :
sentence =("ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY") #This is a list
print (sentence)
text = input("Choose a word from the sentence above")#this prints out some text with an input
sentence = sentence.split(" ")# This splits the list
text = text.upper ()# this makes the text in capital letters
def lookfor ():
if text in sentence:
for i in sentence:
value = sentence.index(sentence)
print ("Your word has been found in the sentence at the position", value + "and", value )
else:
print ("The word that you have typed is not found in the sentence.")
Thank you
To answer your questions, nothing is happening because you aren't calling the function.
There's a lot of work remaining on your function, but here are some general tips:
1) Index only finds the first instance of an element in a list
2) You can't be sure that a word is in your sentence exactly twice
3) Use descriptive variable names. For example, for word in sentence makes a lot more sense intuitively
You can do something like this:
sentence =("ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY") #This is a list
print (sentence)
text = raw_input("Choose a word from the sentence above: ")#this prints out some text with an input
sentence = sentence.split(" ")# This splits the list
text = text.upper ()# this makes the text in capital letters
def lookfor (text):
indexes = [ idx+1 for word, idx in zip(sentence, range(0,len(sentence))) if text == word ]
print ("Your word has been found in the sentence at these positions", indexes )
if not indexes:
print ("The word that you have typed is not found in the sentence.")
lookfor(text)
Example:
ASK NOT WHAT YOUR CONTRY CAN DO FOR ASK WHAT YOU CAN DO FOR YOUR CONTRY
Choose a word from the sentence above: for
('Your word has been found in the sentence at these positions', [8, 14])
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
currently I faced issue with python code
I have two questions relate with "def" code.
1)
I need to print out 6 alphabet which is "K,E,Y,S,N,O"
slimier like under sample
enter image description here
2)
how can I print out this alphabet if user typing one word like "KEY" then print out *mark with KEY
or If user typing "BED" then print out "E"only because we only have alphabet with K,E,Y,S,N,O
if can anyone help me with this two questions? I appreciate that
Thanks
Question 1 need work with 2-dimensional list (list with lists for rows) and I skip this problem.
As for Question 2 you can filter chars in word.
You can treat string "BED" as list of chars (even without using list("BED")) and you can use it in for-loop to check every char with list ["K","E","Y","S","N","O"] (or "KEYSNO") and skip chars "B" and "D"
#my_chars = "KEYSNO" # also works
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
for char in word:
if char in my_chars:
print(char, "- OK")
else:
print(char, "- unknown")
Result:
B - unknown
E - OK
D - unknown
This way you can create new list to keep only correct chars
my_chars = ["K","E","Y","S","N","O"]
word = "BED"
filtered_chars = []
for char in word:
if char in my_chars:
filtered_chars.append(char)
print(filtered_chars)
Result:
['E']
In Python you can write it even shorter using list comprehension
filtered_chars = [char for char in word if char in my_chars]
Eventually you can write it with function filter() like
filtered_chars = list(filter(lambda char: char in my_chars, word))
How can I capitalize the first letter of a input sentence in python?
Output has to be: Enter sentence to be capitalized:+ input sentence
input_string =input("Enter sentence to be capitalized: ")
def capitalize_first(input_string):
output=input_string.split('.')
i=0
while i<len(output)-1:
result=output[i][0].upper()+output[i][1:]+"."
print("Enter sentence to be capitalized:"+result)
How about input_string.title()?
input_string =input("Enter sentence to be capitalized: ")
def capitalize_first(input_string):
result = input_string.title()
print("Enter sentence to be capitalized:"+result)
This built-in method only capitalises the first character and keeps other ones lower, just like how titles work.
As you can see, the extra capitals in THIS IS AN AMAZING are changed.
>>> input_string = "Hello World THIS IS AN AMAZING day!!!"
>>> input_string.title()
>>> 'Hello World This Is An Amazing Day!!!'
In my opinion there are many ways to do so, but title() is the easiest. You can use upper() inside a for loop which iterating the input string, or even capitalize(). If the goal is to capitalise only the first letter of every word. Then you can't use above methods since they capitalise the word in traditional way (first letter is capitalise and others in simple letters regardless what user entered). To avoid that and keep any capitalise letters inside a word as it is, just like user entered.
Then this might be a solution
inputString=input("Your statement enter value or whatever")
seperatedString=inputString.split()
for i in seperatedString:
i[0].upper()
print("Anything you want to say" + i)
sentence="test Sentence"
print(sentence.title()) #makes the first letter of every word in sentence capital
print(sentence[0].upper()+sentence[1:] ) #retains case of other charecters
print(sentence.capitalize()) #makes all other charecters lowercase
Output:
Test Sentence
Test Sentence
Test sentence
Answer your specific question
def modify_string(str1):
sentence_list=str1.split('.')
modify_this=input("Enter sentence to be modified: ")
for idx, item in enumerate(sentence_list):
modify_this_copy=modify_this
if item.lower().strip()==modify_this.lower().strip():
sentence_list[idx]=modify_this_copy[0].upper()+modify_this_copy[1:]
return '. '.join(sentence_list)
string1="hello. Nice to meet you. hello. Howdy."
print(modify_string(string1))
Output
Enter sentence to be modified: hello
Hello. Nice to meet you. Hello. Howdy.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
If I have some text like:
text= " First sentence. Second sentence. Third sentence."
And after this I split by '.':
new_split = text.split('.')
I will receive: ['First sentence', Second sentence','Third sentence']
How could I print entire second sentence if I call it?
Like:
if 'second' in new_split : print (new_split[GET SECOND SENTENCE])
I would like to know how to get entire 'second sentence' if I know in my split there exists a sentence that contains my keyword.
To find the index of the first sentence in a list of sentences which is containing a given substring:
i = next(i for i, sentence in enumerate(sentences) if word in sentence)
The same thing with simple Python:
for i, sentence in enumerate(sentences):
if word in sentence:
break
else:
# the word is not in any of the sentences
text= " First sentence. Second sentence. Third sentence."
[print(i) for i in text.split('.') if "second" in i.lower()]
which prints:
Second sentence
Above is the shortest way I could think of doing it in terms of lines, but you just as easily do it with a for-loop rather than a list-comp:
for sentence in text.split('.'):
if "second" in sentence.lower():
print(sentence)
You can try this:
text= " First sentence. Second sentence. Third sentence."
new_text = [i for i in text.split('.') if "second" in i.lower()][0]
Output:
' Second sentence'
if new_split[1] != '':
print(new_split[1])
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to check in a sentence if there are elongated words. For example, soooo, toooo, thaaatttt, etc. Now I dont know what the user might type because I have a list of sentences which may or may not have elongated words. How do I check that in python. I am new to python.
Try this:
import re
s1 = "This has no long words"
s2 = "This has oooone long word"
def has_long(sentence):
elong = re.compile("([a-zA-Z])\\1{2,}")
return bool(elong.search(sentence))
print has_long(s1)
False
print has_long(s2)
True
#HughBothwell had a good idea. As far as I know, there is not a single English word that has the same letter repeat three consecutive times. So, you can search for words that do this:
>>> from re import search
>>> mystr = "word word soooo word tooo thaaatttt word"
>>> [x for x in mystr.split() if search(r'(?i)[a-z]\1\1+', x)]
['soooo,', 'tooo', 'thaaatttt']
>>>
Any you find will be elongated words.
Well, you can make a list of every elongated word logically possible. Then loop through the words in the sentence then the words in the list to find elongated words.
sentence = "Hoow arre you doing?"
elongated = ["hoow",'arre','youu','yoou','meee'] #You will need to have a much larger list
for word in sentence:
word = word.lower()
for e_word in elongated:
if e_word == word:
print "Found an elongated word!"
If you wanted to do what Hugh Bothwell said, then:
sentence = "Hooow arrre you doooing?"
elongations = ["aaa","ooo","rrr","bbb","ccc"]#continue for all the letters
for word in sentence:
for x in elongations:
if x in word.lower():
print '"'+word+'" is an elongated word'
You need to have a reference of valid English words available. On *NIX systems, you could use /etc/share/dict/words or /usr/share/dict/words or equivalent and store all the words into a set object.
Then, you'll want to check, for every word in a sentence,
That the word is not itself a valid word (i.e., word not in all_words); and
That, when you shorten all consecutive sequences to one or two letters, the new word is a valid word.
Here's one way you might try to extract all of the possibilities:
import re
import itertools
regex = re.compile(r'\w\1\1')
all_words = set(get_all_words())
def without_elongations(word):
while re.search(regex, word) is not None:
replacing_with_one_letter = re.sub(regex, r'\1', word, 1)
replacing_with_two_letters = re.sub(regex, r'\1\1', word, 1)
return list(itertools.chain(
without_elongations(replacing_with_one_letter),
without_elongations(replacing_with_two_letters),
))
for word in sentence.split():
if word not in all_words:
if any(map(lambda w: w in all_words, without_elongations(word)):
print('%(word) is elongated', { 'word': word })
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
I have this code:
mylist = open('sortedwords.txt')
txt = mylist.read()
mylist = txt.split()
stuff = input('Type a word here: ')
def removeletters (word, Analysis):
for char in range (len(Analysis)):
if Analysis [char] in word:
word = word.replace(Analysis[char],"",1)
return word
def anagramSubset(word, textList):
newWord = word
for char in range(len(textList)):
if textList[char] not in newWord:
return False
else:
newWord = newWord.replace(textList[char],"",1)
return True
def anagram(word, textList):
savedWords =[]
for checkword in textList:
if len(word) == len(checkword) and anagramSubset(word, checkword):
savedWords.append(checkword)
print(checkword)
anagram(stuff, mylist)
It is supposed to take an input word, remove letters from the input word, then make a subset of words and save that to an array to print off of.
The problem is that the code will save every word that can be created from the input. E.g. an input of spot results in top, tops, stop, pots, pot, etc. The result should only have tops, pots, and stop.
What is wrong with the code, and how do I fix it?
I looked at the code and am wondering what the recursion is adding? The first pass does all of the computational work and then the recursion adds some extra stack frames and alters how output is printed. Am I making the wrong assumption that textList is a list of valid words split from a single line in a file?
When I run this locally with a particular word list, this gets the same effect (in the sense that it finds words whose letters are a subset) with less thrashing:
def anagram(word, textList):
savedWords = []
for checkword in textList:
if anagramSubset(word, checkword):
savedWords.append(checkword)
print(savedWords)
If the problem eventually becomes that you're getting words that have too few letters, you could fix your problem by checking that a word is the length of the original word before you add it with:
if len(original_word) == len(checkword):
savedWords.append(checkword)