Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I understand there is sort() function, but it won't work for me here. I would like to order alphabetically a string like follows:
'S NOM V NOUN VERB'
It should be:
'NOM NOUN S VERB V'
How can I achieve that in python?
Edit:
I have tried:
''.join(sorted(m[i][j]))
But this returned with very changed output like ABEILMNNNNOOPRSUVV for example which doesn't make sense.
You already have at least one good answer. You might as well abstract it into a function:
def sortWords(s, delim = ' '):
return delim.join(sorted(s.split(delim)))
For example,
>>> sortWords('S NOM V NOUN VERB')
'NOM NOUN S V VERB'
Try the following:
x = 'S NOM V NOUN VERB'
x = x.split() # produces ['S', 'NOM', 'V', 'NOUN', 'VERB']
x = sorted(x) # produces ['NOM', 'NOUN', 'S', 'V', 'VERB']
x = ' '.join(x) # produces 'NOM NOUN S V VERB'
You will have to use a custom sorting function if you want the order of V and VERB to be reversed (see the 'key' keyword for the sorted function).
You should split the string into a list then sort it and turn it back into a string. Here is an example.
old_string = "hello world abc"
string_list = old_string.split(" ") # split the string by a space, you can choose something different.
new_string = " ".join(string_list.sort()) # join list by a space.
print(new_string)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
in my code I have this line which return a string
return item.title().lower()
item is an object, with a title, and we return that string title but in all lowercase.
How can I do something like
return item.title().lower()
but if the words (Maxine, Flora, Lindsey) are in that title, keep them uppercase.
All the other words, do lowercase
I can use an if statement but I'm not really sure how to capitalize only specific words.
like
names= ("Maxine", "Mrs. Lichtenstein", "string3")
if any(s in item.title() for s in names):
return ???
would something like that work? And what could I return?
The following should work (considering that there is no occurence of these words with first character as lowercase (eg maxine) or there is and you want it to upper):
def format(s):
s=s.lower()
for i in ('maxine', 'flora', 'lindsey'):
if i in s:
s=s[:s.find(i)]+i[0].upper()+i[1:]+s[s.find(i)+len(i):]
return s
Example:
item.title='My name is Maxine i LIVE IN Flora and I LOVE Lindsey'
>>> format(item.title)
'my name is Maxine i live in Flora and i love Lindsey'
You're on the right track to use an if statement to check the word against a list of things to keep. Try something like this:
def lowercase_some(words, exclude=[]):
# List of processed words
new_words = []
for word in words:
if word.lower() in exclude:
# If the word is in our list of ones to exclude, don't convert
new_words.append(word)
else:
new_words.append(word.lower())
return new_words
>>> lowercase_some(['TEST', 'WORDS', 'MEXICO'], ['mexico'])
['test', 'words', 'MEXICO']
This can be done in a very Python-ic way with list-comprehension:
def lowercase_some(words, exclude=[]):
return [word.lower() if word.lower() not in exclude else word for word in words]
you can use this:
names = ['Maxine', 'Flora', 'Lindsey']
if item.title() in names:
return item.title()
else:
return item.title.lower()
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
Input 1 - 'My name is Mayank'
Input 2 - 'My will name not Mayank'
Output - 'My will name is not Mayank' or 'My will name not is Mayank'
I want to combine two string, both of them may contain some extra words (which is missing in the other). If there are multiple outputs, then please give any.
Please provide any hints or code in Python or C++.
Update - Order of words should be maintained, and it is given that all the common words will be in same order in both the inputs.
If you keep note of the set of words preceding every word in each sentence you get
{'My': set(),
'name': {'My', 'will'},
'is': {'My', 'name'},
'Mayank': {'My', 'is', 'name', 'not', 'will'},
'will': {'My'},
'not': {'My', 'name', 'will'}}
You can then iterate on the list generating words whose complete set of preceding words have already been generated.
Here's the Python:
from collections import defaultdict
s1 = 'My name is Mayank'
s2 = 'My will name not Mayank'
s = [s1.strip().split(), s2.strip().split()]
keyaftervalues = defaultdict(set)
for phrase in s:
for i, this in enumerate(phrase):
keyaftervalues[this] |= set(phrase[:i])
keyaftervalues = dict(keyaftervalues)
sofar, sofarlist = set(), []
while keyaftervalues:
consider = []
for this, preceders in keyaftervalues.items():
if sofar.issuperset(preceders):
others = preceders - sofar
consider.append((this, len(others), len(preceders)))
if consider:
consider.sort(key=lambda x:x[1:])
last = consider[0][0]
sofar.add(last)
sofarlist.append(last)
del keyaftervalues[last]
answer = ' '.join(sofarlist)
print(answer) # My will name is not Mayank
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How to choose
[Andrey] and [21] from info?
info = "my name is [Andrey] and I am [21] years old"
result = ["[Andrey]", "[21]"];
I am sure other ways would be better. But I tried this and it worked.
If you want to extract characters inside [] without knowing its position, you can use this method:
Run a for loop through string
If you find character [
append all the next characters in a string until you find ]
you can add these strings in a list to fetch result together. Here is the code.
info = "my name is [Andrey] and I am [21] years old"
s=[] #list to collect searched result
s1="" #elements of s
for i in range(len(info)):
if info[i]=="[":
while info[i+1] != "]":
s1 += info[i+1]
i=i+1
s.append(s1)
s1=""
#make s1 empty to search for another string inside []
print s
Output will be:
['Andrey', '21']
You may choose to regex method.
Or simply use list comprehension for your use case here:
>>> print([ lst[index] for index in [3,7] ])
['[Andrey]', '[21]']
But another way, You first convert your string to list and then choose by index method with the help of itemgetter:
>>> info = "my name is [Andrey] and I am [21] years old"
>>> lst = info.split()
>>> lst
['my', 'name', 'is', '[Andrey]', 'and', 'I', 'am', '[21]', 'years', 'old']
>>> from operator import itemgetter
>>> print(itemgetter(3,7)(lst))
('[Andrey]', '[21]')
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
The desired result is either a function or a way to find where is a sentence within a list of strings.
sentence = 'The cat went to the pool yesterday'
structure = ['The cat went,', 'to the pool yesterday.','I wonder if you realize the effect you are having on me. It hurts. A lot.']
for example
def findsentence(sentence, list of strings):
# do something to get the output, vec of positions to find the sentence in hte string list
return output
findsentence(sentence, structure)
> (0,1) # beacuse the phrase is splitted in the list...
Caution!!
The challenge it is not to find exactly the sentence. Look at the example, this sentence is part of sentence position 0 and part in structure postition 1.
So this is not a simple, string manipulation problem.
Use the following :
sentence = "foo sam bar go"
structure = ["rq", "foo sam", "bar go", "ca", "da"]
def findsentencelist(sentence, list_of_strings):
l = []
for item in list_of_strings:
if item in sentence:
l.append(list_of_strings.index(item))
return l
print str(findsentencelist(sentence, structure))
Hopefully this will help you, Yahli.
EDIT :
There is a problem with your variables.
Your sentence MUST be a string - not a list.
Edit your variables and try this function again :)
SECOND EDIT:
I think I've finally understood what you're trying to do. Let me know if this one works better.
THIRD EDIT:
Jesus, Hopefully this one would solve your problem. Let me know if it did the trick :)
I just remove punctuations on structure to make it work:
sentence = 'The cat went to the pool yesterday'
structure = ['The cat went,', 'to the pool yesterday.','I wonder if you realize the effect you are having on me. It hurts. A lot.','Life is too short as it is. In short, she had a cushion job.']
import string
def findsentence(sentence, list_of_strings):
return tuple(i for i, s in enumerate(list_of_strings) if s.translate(None, string.punctuation) in sentence)
print findsentence(sentence, structure)
# (0, 1)
After removing the punctuation. You can use this code to get the index ,
for i,j in enumerate(structure):
if j in sentence:
print(i)
Hope this solves your problems. There are quite other solutions as python is flexible.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have values that look like this
<type 'str'>
['zeven', 'nul', 'zeven', 'een', 'pieter', 'marie']
What I would like to do now is to loop over all the elements. However if I do like this:
x = ['zeven', 'nul', 'zeven', 'een', 'pieter', 'marie']
for word in x:
print(x)
I get:
[
'
z
e
Any thoughts how I can just get the values (like zeven, nul... etc...)
You are almost there, you should not print x but you should print word for each word in the list.
x = ['zeven', 'nul', 'zeven', 'een', 'pieter', 'marie']
for word in x:
print(word)
this will give you the following output:
zeven
nul
zeven
een
pieter
marie
It looks like you have something like this:
x = "['zeven', 'nul', 'zeven', 'een', 'pieter', 'marie']"
So you will need to use eval():
for word in eval(x):
print word