As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?
This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.
def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string).
You can use string.lowercase, as other posters have suggested:
import string
allTheLetters = string.lowercase
To do things the way you're "used to", treating letters as numbers, you can use the "ord" and "chr" functions. There's absolutely no reason to ever do exactly this, but maybe it comes closer to what you're actually trying to figure out:
def getAllTheLetters(begin='a', end='z'):
beginNum = ord(begin)
endNum = ord(end)
for number in xrange(beginNum, endNum+1):
yield chr(number)
You can tell it does the right thing because this code prints True:
import string
print ''.join(getAllTheLetters()) == string.lowercase
But, to solve the problem you're actually trying to solve, you want to use a dictionary and collect the letters as you go:
from collections import defaultdict
def letterOccurrances(string):
frequencies = defaultdict(lambda: 0)
for character in string:
frequencies[character.lower()] += 1
return frequencies
Use like so:
occs = letterOccurrances("Hello, world!")
print occs['l']
print occs['h']
This will print '3' and '1' respectively.
Note that this works for unicode as well:
# -*- coding: utf-8 -*-
occs = letterOccurrances(u"héĺĺó, ẃóŕĺd!")
print occs[u'l']
print occs[u'ĺ']
If you were to try the other approach on unicode (incrementing through every character) you'd be waiting a long time; there are millions of unicode characters.
To implement your original function (print the counts of each letter in alphabetical order) in terms of this:
def alphCount(text):
for character, count in sorted(letterOccurrances(text).iteritems()):
print "%s: %s" % (character, count)
alphCount("hello, world!")
the question is how to make
allTheLetters equal to said letters
without something like allTheLetters =
"abcdefg...xyz"
That's actually provided by the string module, it's not like you have to manually type it yourself ;)
import string
allTheLetters = string.ascii_lowercase
def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
If you just want to do a frequency count of a string, try this:
s = 'hi there'
f = {}
for c in s:
f[c] = f.get(c, 0) + 1
print f
For counting objects, the obvious solution is the Counter
from collections import Counter
import string
c = Counter()
for letter in text.lower():
c[letter] += 1
for letter in string.lowercase:
print("%s: %d" % (letter, c[letter]))
Do you mean using:
import string
string.ascii_lowercase
then,
counters = dict()
for letter in string.ascii_lowercase:
counters[letter] = lowertext.count(letter)
All lowercase letters are accounted for, missing counters will have zero value.
using generators:
counters =
dict( (letter,lowertext.count(letter)) for letter in string.ascii_lowercase )
Something like this?
for letter in range(ord('a'), ord('z') + 1):
print chr(letter) + ":", lowertext.count(chr(letter))
Main question is "iterate through the alphabet":
import string
for c in string.lowercase:
print c
How get letter frequencies with some efficiency and without counting non-letter characters:
import string
sample = "Hello there, this is a test!"
letter_freq = dict((c,0) for c in string.lowercase)
for c in [c for c in sample.lower() if c.isalpha()]:
letter_freq[c] += 1
print letter_freq
How about this, to use letters, figures and punctuation (all usable to form a Django key):
import random
import string
chars = string.letters + string.digits + string.punctuation
chars_len = len(chars)
n = 40
print(''.join([chars[random.randint(0, chars_len)] for i in range(n)]))
Example result: coOL:V!D+P,&S*hzbO{a0_6]2!{4|OIbVuAbq0:
Just use:
import string
string.lowercase
string.uppercase
or
string.letters[:26]
string.letters[26:]
This is what I do:
import string
for x in list(string.lowercase):
print x
Related
I want to create an encryption script that encrypts the string given to it, here's how it went.
# First, I created a list of the string I got
string = '16271'
string_list = []
for letter in string:
string_list.append(letter)
Then, I have a list called encrypt_list which the letters which I want to add in order to encrypt my string.
So, I use the following code to add a random letter from the encrypt_list after each letter/component in the string_list and then join the list and print as a string.
for i in range(0, len(string) - 1):
string_list.insert(for letter in string_list: string_list.index(letter) + 1, encrypt_list[random.randint(0, len(encrypt_list) - 1)])
print("The encrypted string is: ")
print(''.join(string_list))
I expected the output to be: 1A6b2n781 (I bolded the letter to show my actual string in it) But I am getting an error, that I cannot use the for loop in the insert function, and I cannot find another way of doing that, please help. Hope I make my problem clear
Not sure what your encrypted_list looks like, but if it's a list of letters, this would work:
import random
string = '16271'
encrypted_list = ['r', 't', 's', 'o', 'j', 'e']
encrypted_string = ''.join([s + random.choice(encrypted_list) for s in string])
Something like this?
# First, I created a list of the string I got
import random
string = '16271'
string_list = []
for letter in string:
string_list.append(letter)
the_other_list = ['lorem', 'dorem', 'forem', 'borem']
for i in range(0, len(the_other_list)):
the_other_list[i] = string_list[random.randint(0, len(string_list) - 1)] + the_other_list[i]
print(''.join(the_other_list))
Result example: 1lorem2dorem2forem7borem
You can use a for loop, adding one letter to the list at a time, then adding a randomly selected letter immediately afterwards (if we're not processing the last letter in the list). I've used constants from string to define the space of characters to sample from; you can adjust this as you see fit.
This should be simpler than trying to do repeated insertion in the middle of the list (where you'd have to handle memory shifting as you're inserting, plus it'd get slower for larger texts because you'd be attempting to insert in the middle of a list).
# First, I created a list of the string I got
import random
import string
encrypt_text = string.ascii_uppercase + string.ascii_lowercase + string.digits
plaintext = '16271'
letters = []
for index, letter in enumerate(plaintext):
letters.append(letter)
if index != len(plaintext) - 1:
letters.append(random.choice(encrypt_text))
print("The encrypted string is: ")
print(''.join(letters))
Based on how you defined the problem, I would recommend implementing it as a generator:
import random
import string
def _gen_string(s):
alphabet = string.ascii_letters
for c in s:
yield c
yield random.choice(alphabet)
Then you can use that as the basis for your encryption:
def encrypt(s):
return ''.join(_gen_string(s))
encrypt('16271')
# 1J6P2U7Z1i
Of course, this is not really encryption. It's obscurity and obscurity is not a form of security that should be relied upon :-)
Objective: count by letters instead of integers.
Is there a clean way to count-by-letters in Python-2.7? I have a program where I am enumerating some data by letter, and my solution would not be very clear to someone reading my code.
I've been checking through the standard documentation, but I don't see anything built-in.
What I'm looking for:
for count in range('A', 'G'):
print count
output[1]:
'C'
'D'
'E'
'F'
How I would do it:
Solution A: Use a dictionary
letters = {
1:'A'
2:'B'
3:'C'
...
}
for count in range(2, 6):
print letters[count]
Solution B: Use chr() and ord()
for count in range(2, 6):
print chr(ord('A') + count)
Relevance:
I am working on a sunday paper crytogram solver. Part of my algorithm involves classifying words by their letter code. For example,
print letter_code('banana')
output[2]: 'ABCBCB'
import string
alphabet = string.ascii_uppercase
>>> for char in alphabet[2:6]:
... print char
...
C
D
E
F
>>>
Your Solution B could be expressed:
for charcode in range(ord('B'), ord('G')):
print chr(charcode)
But to attack your larger issue, how about:
from string import ascii_lowercase, ascii_uppercase
def letter_code(string):
indexes = [ascii_lowercase.index(letter) for letter in string]
return "".join(ascii_uppercase[indexes.index(number)] for number in indexes)
print letter_code('banana')
Gives you "ABCBCB"
Here is a function that would do what you wish:
import string
def enumerate(first, last):
alphabet = string.ascii_uppercase
start = alphabet.index(first)
while alphabet[start] != last:
print alphabet[start]
start += 1
print last
Another solution I have become fond of for my particular application is:
alphabet = iter('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
print next(alphabet)
I'm writing a program to encrypt a string input. I have a random number generator, and some code that converts the random number into a letter. How would I go about inserting this letter after every say, 3rd letter? I.e. String before: abcdef , String after: abcldefk.
Code for the random number generator if it helps:
Letter = random.randrange(1,26)
print chr(Letter + ord('A'))
You can use str.join, enumerate with a start index equal to 1 and modulo:
print("".join([x if i % 3 else x + random_letter for i, x in enumerate(s,1)]))
If you just want to insert a random letter, you can use string.ascii_letters and random.choice:
from random import choice
from string import ascii_letters
s = "abcdef"
print("".join([x if i % 3 else x + choice(ascii_letters) for i, x in enumerate(s,1)])
abcQdefN
I was inspired by Padraic's answer and wanted to add a little bit more.
import random
Letter = random.randrange(1,26)
def encrypt_string(string, n):
return ("".join([x if i % n else chr(Letter + ord('A')) for i, x in enumerate(string)]))
Here is a string "encryption" (using it loosely) method for every 'nth' letter.
Results (Answers may vary due to random):
print(encrypt_string("0123456789", 2)) # Every other letter
M1M3M5M7M9
print(encrypt_string("0123456789", 3)) # Every third letter
D12D45D78D
I hope this helped.
Okay so what I did was
def countvowels(st):
result=st.count("a")+st.count("A")+st.count("e")+st.count("E")+st.count("i")+st.count("I")+st.count("o")+st.count("O")+st.count("u")+st.count("U")
return result
This works(I'm aware indentation might be wrong in this post, but the way I have it indented in python, it works).
Is there a better way to do this? Using for loops?
I would do something like
def countvowels(st):
return len ([c for c in st if c.lower() in 'aeiou'])
There's definitely better ways. Here's one.
def countvowels(s):
s = s.lower()
return sum(s.count(v) for v in "aeiou")
You can do that using list comprehension
def countvowels(w):
vowels= "aAiIeEoOuU"
return len([i for i in list(w) if i in list(vowels)])
You could use regex pattern to do this easily. But it looks to me, that you want to do it without. So here is some code to do so:
string = "This is a test for vowel counting"
print [(i,string.count(i)) for i in list("AaEeIiOoUu")]
you can do it in various ways, first look in google before asking, i had copy pasted 2 of them
def countvowels(string):
num_vowels=0
for char in string:
if char in "aeiouAEIOU":
num_vowels = num_vowels+1
return num_vowels
data = raw_input("Please type a sentence: ")
vowels = "aeiou"
for v in vowels:
print v, data.lower().count(v)
You can also try Counter from collections (only available from Python 2.7+) as shown below . It'll show how many times each letter has been repeated.
from collections import Counter
st = raw_input("Enter the string")
print Counter(st)
But you want vowels specifically then try this.
import re
def count_vowels(string):
vowels = re.findall('[aeiou]', string, re.IGNORECASE)
return len(vowels)
st = input("Enter a string:")
print count_vowels(st)
Here is a version using map:
phrase=list("This is a test for vowel counting")
base="AaEeIiOoUu"
def c(b):
print b+":",phrase.count(b)
map(c,base)
I've made a simple script in python which shifts the letters up 5 spaces in the ASCII table using chr and ord. See below:
word = "python"
print 'Shifted 5 letters are: '
for letters in word:
print chr(ord(letters)+5),
The output is:
Shifted 5 letters is:
u ~ y m t s
The output is great, but how do I stop the for loop putting spaces in-between each letter?
If you don't need to use the for loop, simply do this:
print ''.join([chr(ord(letter) + 5) for letter in word])
instead of the whole loop.
There is no way to stop Python 2.x's print statement from printing a space when you use the "magic comma".
This is part of the reason Python 3.x's print function is more flexible, using keyword arguments instead of magic syntax:
for letters in word:
print(chr(ord(letters)+5), end='')
If you really want to, you can get the same behavior in Python 2.x with from __future__ import print_function (or by using the third-party six library).
However, usually, when you're having problem fighting with print to do what you want, the solution is to format your string first, then print it. So:
output = ''
for letters in word:
output += chr(ord(letters)+5)
print output
It's generally more pythonic (and faster) to build up a list of strings, and calling join at the end, instead of repeatedly appending to a string:
output = []
for letters in word:
output.append(chr(ord(letters)+5))
print ''.join(output)
And you can make that simpler (and even more fasterer) by turning the loop into a comprehension instead of a statement:
print ''.join(chr(ord(letters) + 5) for letters in word)
I don't know if I get what you're asking 100 % but this work-around returned the letters without any whitespace :
def no_space(word) :
new_word = ""
for letter in word :
new_word += chr(ord(letter) + 5)
return new_word
Then call the function :
no_space("python")
Result : 'u~ymts'