So im new at python and i would like some help in making code where:
When an input is typed if the input has a minimum of three words that match any one thing on a list it would replace the input with the text in the list that matches the criteria
Example:
Jan
-Scans List-
-Finds Janice-
-Replaces and gives output as Janice Instead of Jan-
Janice
So far
getname = []
for word in args
room.usernames.get(args,word)
Room.usernames is the list and args input
Error List item has no attribute .get
there is a module used and its ch.py located at http://pastebin.com/5BLZ0UA0
You will need to:
make a replacement words dictionary
get some input
do sanity checking to make sure it fits your parameters
split it into a list
loop through your new list and replace each word with its replacement in your dict, if it is in there
I won't write all of this for you. But here's a tip for how to do that last part: use the get method of dicts - it allows you to provide a "fallback" in case the word is not found in the dict. So just fall back to the word itself.
replacement_words = {'jan':'janice','foo':'bar'}
my_list = ['jan','is','cool']
[replacement_words.get(word,word) for word in my_list]
Out[41]: ['janice', 'is', 'cool']
You Could try this
getname = []
for word in args
"%s"% (room.usernames).get(args,word)
Related
I am trying to order a word's letters by alphabetically in Python. But there is a comma at the end of the output.(I tried ''.sort() command, it worked well but there is square brackets at the beginning and at the end of the output). The input and the output must be like this:
word
'd','o','r','w'
This is my code:
alphabet='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
word=str(input())
for i in alphabet:
for j in word:
if i==j:
print("'{}',".format(i),end='')
And this is my output:
word
'd','o','r','w',
Python strings have a join() function:
ls = ['a','b','c']
print(",".join(ls)) # prints "a,b,c"
Python also has what is called a 'list comprehension', that you can use like so:
alphabet='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
word=str(input())
matches = [l for l in word if l in alphabet]
print(",".join(sorted(matches)))
All the list comprehension does is put l in the list if it is in alphabet. All the candidate ls are taken from the word variable.
sorted is a function that will do a simple sort (though more complex sorts are possible).
Finally; here are a few other fun options that all result in "a,b,c,d":
"a,b,c,d,"[:-1] . # list-slice
"a,b,c,d,".strip(",") . # String strip
you store it in an array and then print it at the end
alphabet='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
word=str(input())
matches = []
for i in alphabet:
for j in word:
if i==j:
matches.append("'{i}',".format(i=i))
#now that matches has all our matches
print(",".join(arrayX) # join it
or as others have mentioned
print(",".join(sorted(word)))
You want to use the string.join() function.
alphabet='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
','.join(alphabet)
There's really no need to anything to make the string into a list, join will iterate over it quite happily. Tried on python 2.7 and 3.6
Doing it your self
The trick is in the algorithm you use.
You want to add a comma and a space, after each field, except the last. But it is hard to know which is the last, until it is too late.
It would be much easier if you could make the first field the special case, as this is mach easier to predict.
Therefore transform the algorithm to: Add a comma and a space, before each field, except the first. This produces the same output, but is a much simpler algorithm.
Use a library
Using a library is always preferable (unless doing it just for the practice).
python has the join method. See other answers.
I am trying to write a program to read a text document and output the longest word in the document. If there are multiple longest words (i.e., all of equal length) then I need to output them all in the same order in which they occur. For example, if the longest words were dog and cat your code should produce:
dog cat
I am having trouble finding out how to select numerous words of equal max length and print them. This is as far as I've gotten, I am just struggling to think of how to select all words with equal max length:
open the file for reading
fh = open('poem.txt', 'r')
longestlist = []
longestword = ''
for line in fh:
words = (line.strip().split(' '))
for word in words:
word = ''.join(c for c in word if c.isalpha())
if len(word) > (longestword):
longest.append(word)
for i in longestlist:
print i
Ok, first off, you should probably use a with as statement, it just simplifies things and makes sure you don't mess up. So
fh = open('poem.txt', 'r')
becomes
with open('poem.txt','r') as file:
and since you're just concerned with words, you might as well use a built-in from the start:
words = file.read().split()
Then you just set a counter of the max word length (initialized to 0), and an empty list. If the word has broken the max length, set a new maxlength and rewrite the list to include only that word. If it's equal to the maxlength, include it in the list. Then just print out the list members. If you want to include some checks like .isalpha() feel free to put it in the relevant portions of the code.
maxlength = 0
longestlist = []
for word in words:
if len(word) > maxlength:
maxlength = len(word)
longestlist = [word]
elif len(word) == maxlength:
longestlist.append(word)
for item in longestlist:
print item
-MLP
What you need to do is to keep a list of all the longest words you've seen so far and keep the longest length. So for example, if the longest word so far has the length 5, you will have a list of all words with 5 characters in it. As soon as you see a word with 6 or more characters, you will clear that list and only put that one word in it and also update the longest length. If you visited words with same length as the longest you should add them to the list.
P.S. I did not put the code so you can do it yourself.
TLDR
Showing the results for a file named poem.txt whose contents are:
a dog is by a cat to go hi
>>> with open('poem.txt', 'r') as file:
... words = file.read().split()
...
>>> [this_word for this_word in words if len(this_word) == len(max(words,key=len))]
['dog', 'cat']
Explanation
You can also make this faster by using the fact that <file-handle>.read.split() returns a list object and the fact that Python's max function can take a function (as the keyword argument key.) After that, you can use list comprehension to find multiple longest words.
Let's clarify that. I'll start by making a file with the example properties you mentioned,
For example, if the longest words were dog and cat your code should produce:
dog cat
{If on Windows - here I specifically use cmd}
>echo a dog is by a cat to go hi > poem.txt
{If on a *NIX system - here I specifically use bash}
$ echo "a dog is by a cat to go hi" > poem.txt
Let's look at the result of the <file-handle>.read.split() call. Let's follow the advice of #MLP and use the with open ... as statement.
{Windows}
>python
or possibly (with conda, for example)
>py
{*NIX}
$ python3
From here, it's the same.
>>> with open('poem.txt', 'r') as file:
... words = file.read().split()
...
>>> type(words)
<class 'list'>
From the Python documentation for max
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
Return the largest item in an iterable or the largest of two or more arguments.
If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.
There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.
If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).
New in version 3.4: The default keyword-only argument.
Changed in version 3.8: The key can be None.
Let's use a quick, not-so-robust way to see if we meet the iterable requirement (this SO Q&A gives a variety of other ways).
>>> hasattr(words, '__iter__')
True
Armed with this knowledge, and remembering the caveat, "If multiple items are maximal, the function returns the first one encountered.", we can go about solving the problem. We'll use the len function (use >>> help(len) if you want to know more).
>>> max(words, key=len)
'dog'
Not quite there. We just have the word. Now, it's time to use list comprehension to find all words with that length. First getting that length
>>> max_word_length = len(max(words, key=len))
>>> max_word_length
3
Now for the kicker.
>>> [this_word for this_word in words if len(this_word) == len(max(words,key=len))]
['dog', 'cat']
or, using the commands from before, and making things a bit more readable
>>> [this_word for this_word in words if len(this_word) == max_word_length]
['dog', 'cat']
You can use a variety of methods you'd like if you don't want the list format, i.e. if you actually want
dog cat
but I need to go, so I'll leave it where it is.
everyone. I'm trying to complete a basic assignment. The program should allow a user to type in a phrase. If the phrase contains the word "happy" or "sad", that word should then be randomly replaced by a synonym (stored in a dictionary). The new phrase should then be printed out. What am I doing wrong? Every time I try to run it, the program crashes. This is the error I get:
0_part1.py", line 13, in <module>
phrase["happy"] = random.choice(thesaurus["happy"])
TypeError: 'str' object does not support item assignment
Here is what I have so far:
import random
thesaurus = {
"happy": ["glad", "blissful", "ecstatic", "at ease"],
"sad": ["bleak", "blue", "depressed"]
}
phrase = input("Enter a phrase: ")
phrase2 = phrase.split(' ')
if "happy" in phrase:
phrase["happy"] = random.choice(thesaurus["happy"])
if "sad" in phrase:
phrase["sad"] = random.choice(thesaurus["sad"])
print(phrase)
The reason for your error is that phrase is a string, and strings are immutable. On top of that, strings are sequences, not mappings; you can index them or slice them (e.g., happy_index = phrase.find("happy"); phrase[happy_index:happy_index+len("happy")]), but you can't use them like dictionaries.
If you want to create a new string, replacing the substring happy with another word, use the replace method.
And there's no reason to check first; if happy isn't found, replace wil do nothing.
So:
phrase = phrase.replace("happy", random.choice(thesaurus["happy"]))
While we're at it, instead of explicitly looking up each key, you may want to loop over the dictionary and apply all the synonyms:
for key, replacements in thesaurus.items():
phrase = phrase.replace(key, random.choice(replacements))
Finally, notice that this code will replace all instances of happy with the same replacement. Which I think your intended code was also trying to do. If you want to replace each of them with a separately randomly-chosen synonym, that's a bit more complicated. You could loop over phrase.find("happy", offset) until it returns -1, but a neat trick might make it simpler: split the string around each instance of happy, substitute in a different synonym for each split part, then join them all back together. Like this:
parts = phrase.split("happy")
parts[:-1] = [part + random.choice(thesaurus["happy"]) for part in parts[:-1]]
phrase = ''.join(parts)
Generate a random number from (0..[size of list - 1]). Then, access that index of the list. To get the length of a list, just do len(list_name).
I have this list of strings and some prefixes. I want to remove all the strings from the list that start with any of these prefixes. I tried:
prefixes = ('hello', 'bye')
list = ['hi', 'helloyou', 'holla', 'byeyou', 'hellooooo']
for word in list:
list.remove(word.startswith(prexixes)
So I want my new list to be:
list = ['hi', 'holla']
but I get this error:
ValueError: list.remove(x): x not in list
What's going wrong?
You can create a new list that contains all the words that do not start with one of your prefixes:
newlist = [x for x in list if not x.startswith(prefixes)]
The reason your code does not work is that the startswith method returns a boolean, and you're asking to remove that boolean from your list (but your list contains strings, not booleans).
Note that it is usually not a good idea to name a variable list, since this is already the name of the predefined list type.
Greg's solution is definitely more Pythonic, but in your original code, you perhaps meant something like this. Observe that we make a copy (using list[:] syntax) and iterate over the copy, because you should not modify a list while iterating over it.
prefixes = ('hello', 'bye')
list = ['hi', 'helloyou', 'holla', 'byeyou', 'hellooooo']
for word in list[:]:
if word.startswith(prefixes):
list.remove(word)
print list
print len([i for i in os.listdir('/path/to/files') if not i.startswith(('.','~','#'))])
basically I have a user enter a sentence
eg. "hello, how are you?"
and from a large list it replaces "are" with "am" and "you" with "I". to return:
"hello, how am i?"
problem is i have no idea how to do this.
so my list looks a bit like reflections = [["I, you"],["are","am]] ---> etc.
and so far i've got some code which collects raw input from the user and then calls this function to reply to it.
def reflects_users_string(reply):
reply_list = reply.split()
for _ in reply_list
if ????
????
????
else
print "i don't understand"
from what I understand (noob here) it turns the users input into a list and then compares each item in that list with items in the "reflections" list, then it replaces the identical string in one list with the string next to it eg. "are" with "am"
ive been playing with all sorts of ways to do this but just cant seem to figure it out
Try learning to use list comprehensions, it's a powerful way to filter out lists in make iterations.
Let's try to solve your problems with list comprehensions:
#first we need to create mappings in a dict for your reflections
reflect = {
'you': 'I',
'are': 'am'
}
# After we read user input
user_input = 'hello, how are you ?'
#Now look how we can replace all words in user_input from reflect with one line
reflected = [word for word in [reflect.get(key, key) for key in user_input.split()]]
print ' '.join(reflected)
Let's analyse the list comprehension:
First we split user input into a list user_input.split()
Then we iter through the user input words for key in
user_input.split()
For each word in user input words we query the reflect dict. Using
reflect.get(key, key) is a way to query the reflect dict for key
and if we can't find the key a default value of key is returned
instead.
Finally, we wrap all this comprehension with [word for word in [getting reflected words from user input and a default value of the same word if we can't find it's reflection]]
And Voila !
It's a good start so far. As for next step, make a big dict of all the mappings of words, look up each word in that dict, and replace it if it has a replacement.