How do I replace letters in text using a dictionary? - python

I have a dictionary that looks like this:
Letters = {'a': 'z', 'b': 'q', 'm':'j'}
I also have a block of random text.
How do I get replace the letters in my text with the letter from the dictionary. So switch 'a' to 'z' and 'b' to 'q'.
What I've done so far is returning the wrong output and I can't think of any other way:
splitter = text.split()
res = " ".join(Letters.get(i,i) for i in text.split())
print(res)

What we can do is loop through each character in the string and add either the new character or the original character if the new character is not found.
text = "my text ba"
letters = {'a': 'z', 'b': 'q', 'm': 'j'}
result = ""
for letter in text: # For each letter in our string,
result += letters.get(letter, letter) # Either get a new letter, or use the original letter if it is not found.
If you want, you can also do this with a one-liner!
text = "my text ba"
letters = {'a': 'z', 'b': 'q', 'm': 'j'}
result = "".join(letters.get(letter, letter) for letter in text)
This is a bit confusing, so to break it down, for letter in text, we get either the new letter, or we use the (default) original letter.
You can see the documentation for the dict.get method here.

translation_table = str.maketrans({'a': 'z', 'b': 'q', 'm':'j'})
translated = your_text.translate(translation_table)
This is concise and fast

You're iterating over the words in text, not over the letters in the words.
There's no need to use text.split(). Just iterate over text itself to get the letters. And then join them using an empty string.
res = "".join(Letters.get(i,i) for i in text)

Related

Parsing a list nested within a dictionary for words with similar characters in Python

As my first personal project I am building a Wordle "solver" that comes up with a first guess word then takes an input of the letters that were correct in the word then searches the word list for words with similar characters. To do this I stored each word in a dictionary with the key being the word and the value being each character in the word i.e dodge: [d, o, d, g, e]. I am currently experimenting to get code running that parses through the values of the dictionary to match the characters to the inputted letters but am stumped on how to search through the lists within the dictionary as a loop.
Here's my code for inputting the correct letters:
correct_letters_1 = list(letters for letters in input("Input corrects letters: ").strip().split())
Here's one of my attempts at parsing the dictionary:
for letters in correct_letters_1:
if letters in word_dictionary.values():
print("yes")
I'm pretty sure this problem has something to do with my code parsing the entire lists within the dictionary rather than each individual character but even when I try inputting the whole word, i.e Input Correct Letters: d o d g e; I still don't have any output.
If someone could put a beginner on the right track it would be much appreciated.
You might be looking to compare the whole list, rather than the letters:
correct_letters_1 = list(input("Enter correct letters: ").strip())
# correct_letters_1 is a whole list
if correct_letters_1 in word_dictionary.values():
print("yes")
# Inputting "abc"
>>> correct_letters_1
['a', 'b', 'c']
>>> word_dictionary
{'abc': ['a', 'b', 'c']}
>>> correct_letters_1 in word_dictionary.values()
True
To check if the user's guess is a subset of any of the words:
correct_letters_1 = list(input("Enter correct letters: ").strip())
let_set = set(correct_letters_1)
word_dictionary = {'abc': ['a', 'b', 'c'],
'abcde': ['a', 'b', 'c', 'd', 'e'],
'ab': ['a', 'b'],
'test': ['t', 'e', 's', 't']}
# Check to see if correct_letters_1 is a subset of any word in the dictionary
close_words = ["".join(x) for x in word_dictionary.values() if let_set <= set(x)]
Which can be simplified to:
correct_letters_1 = input("Enter correct letters: ").strip()
let_set = set(correct_letters_1)
words = ["abc", "test", "ab"]
# Check to see if correct_letters_1 is a subset of any word in the list words
close_words = [x for x in words if let_set <= set(x)]

How to sort a list with an exception in Python

I want to sort a dictionary alphabetically but we have other letters in Turkish because of that i can't use sorted() function.
For example we have letter "ç" which comes after letter "c". How can i make letter "ç" comes after letter "c"?
Btw it will not be just 1 letter we have plenty more and dictionary will contain hundereds of words and values.
Here is a simple solution based on the Turkish alphabet:
alphabet = "abcçdefgğhıijklmnoöprsştuüvyz"
words = ["merhaba", "aşk", "köpek", "Teşekkürle"]
sorted_words = sorted(words, key=lambda word: tuple(alphabet.index(c) for c in word.lower()))
This code is able to sort words using the lexicographic order. It also works with words containing capital letters.
You can use key argument for sorted, however the main challenge is how to define which letter is "bigger". Maybe you can use some table of letters' values to sort them. Like this:
LETTER_VALUES = {
...
"c": 100,
"ç": 110
...
}
sorted_ar = sorted(char_array, key=lambda ch: LETTER_VALUES.get(ch1, ord(ch)))
Of course, numbers are just random for example and ord the simplest example for "failure default".
You can achieve this by injecting your own alphabet order, example:
letters = "abcçdefgğhıijklmnoöprsştuüvyz"
letters_dict = {i:letters.index(i) for i in letters}
print(sorted("açobzöğge", key=letters_dict.get))
The above should output:
['a', 'b', 'ç', 'e', 'g', 'ğ', 'o', 'ö', 'z']

How do I check if a sequence of characters exists in a list?

How do I check if a sequence of characters exists in a list?
I have a string with some characters that have sequences that reoccur. I know that strings are immutable so I turn the string into the list. However, I'm not sure how to iterate through the list, find the occurrence and change the first letter of the occurrence.
message: DDMCAXQVEKGYBNDDMZUH
Occurence is: DDM
list: ['D', 'D', 'M', 'C', 'A', 'X', 'Q', 'V', 'E', 'K', 'G', 'Y', 'B', 'N', 'D', 'D', 'M', 'Z', 'U', 'H']
What I have currently is simply turning the message into the list. I've tried different ways, which were unsuccessfully that's what I didn't post it. Not really asking you to write the code but at the least explain how to achieve this.
It's a lot easier to check if a string exists in another string since you can simply use the in operator:
if 'DDM' in message:
# do something
But since your goal is to change the first letter of the occurrence, you can use the str.index method to obtain the index of the occurrence and then assemble a new string with slices of the current string and the new letter:
try:
i = message.index('DDM')
message = message[:i] + new_letter + message[i + 1:]
except ValueError:
raise RuntimeError("Sequence 'DDM' not found in message.")
You can use re.sub():
import re
s = 'DDMCAXQVEKGYBNDDMZUH'
re.sub(r'DDM', '$DM', s)
# $DMCAXQVEKGYBN$DMZUH
A simple solution with a for-loop would be:
msg = 'DDMCAXQVEKGYBNDDMZUH'
occ = 'DDM'
for i in range(len(msg)):
if msg[i:i+len(occ)] == occ:
msg = msg[:i] + 'x' + msg[i+1:]
resulting in xDMCAXQVEKGYBNxDMZUH
This also works with overlapping substrings. For example:
msg = 'AAABAA'
occ = 'AA'
will give xxABxA
The simplest way would be using string replace() function.
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
message = "DDMCAXQVEKGYBNDDMZUH"
print message.replace("DDM", "ABC", 1)
Replace function would replace the first occurrence of DDM in the message string.
output: ABCCAXQVEKGYBNDDMZUH
If I carefully read your question you want to search the first occurrence of DDM in your message and replace the first character of it. In that case use below:
message = "DDMCAXQVEKGYBNDDMZUH"
print message.replace("DDM", "ADM", 1)
output: ADMCAXQVEKGYBNDDMZUH

Use the method is_vowel

Write a value returning method, is vowel that returns true if a given characters is vowel otherwise returns false. Write a program that prompts the user to input a sequence of characters and outputs the number of vowels. Please help me to run this problem and what is the exact code
You can use char in "aeiouAEIOU" to determine if a character is a vowel, and use a list comprehension to produce a list containing only vowels, and find the number of vowels in the input string by finding the length of this list.
string=raw_input()
numOfVowels=len([char for char in string if char in "aeiouAEIOU"])
print(numOfVowels)
Input:
abcdefghijklmnopqrstuvwxyz
Output:
5
make a list of vowel letter to comapre letters in input that user enters:
vowel = ['a', 'e', 'i', 'o', 'u']
user_ask = input("enter a string to count the vowel:\t").casefold()
by using casefold method, you do not need to worry about upper and lowercase letters.
count = 0
new_vowel = []
for i in user_ask:
if i in vowel:
count += 1
new_vowel.append(i)
print("number of vowels\n", count)
you can use counter if you want to print them in a key value pairs, i.e. as a dictionary.
from collections import Counter
dict(Counter(new_vowel))
Output
enter a string to count the vowel: I am trying to learn
number of vowels :
6
and the dictionary form is:
{'i': 2, 'a': 2, 'o': 1, 'e': 1}

how to use a for loop to replacing index useing python

Define a function named encrypt which takes as input a string (which is the name of a text file in the current directory). The function should then print the encrypted content of this file.
Here text encryption is done by replacing every occurence of a vowel with its next in the list 'aeiou'. So 'a' is replaced by 'e', 'e' is replaced by 'i', so on and 'u' is replaced by 'a'. Also each consonant is replaced with its next in the list 'bcdfghjklmnpqrstvwxyz' so 'b' is replaced by 'c', 'c' by 'd' so on and lastly 'z' is replaced by 'b'. The same replacement logic holds for upper case letters. Note that non-alphabetic characters should appear in their original form without modification.
def encrypt (eo):
vowel = 'aeiou'
con = 'bcdfghjklmnpqrstvwxyz'
for eo in vowel (t[i+1]):
res=
return res
This piece of code could be useful. Pay attention to the vowel and con content. I appended one letter in each variable vowel and com to avoid the modulo operation. Assume the eo is the input string.
def encrypt (eo):
vowel = 'aeioua'
con = 'bcdfghjklmnpqrstvwxyzb'
encrytTable = vowel + con
res = ""
for letter in eo:
res += encrytTable[encrytTable.find(letter)+1]
return res
If eo is the input filename, you need some file read operation like:
>>> fh = open(eo)
>>> fh.read()
>>> fh.>>> fh.close()
And a more effient way to do it, is pre-compute a encryptTable array and use the table to replace the origianl input in a linear manner. In following code, I assume your input only include lower-case letters. Abd if the shift distance is not 1, you need to modify the code. Pre-compute:
>>> vowel = 'aeioua'
>>> con = 'bcdfghjklmnpqrstvwxyzb'
>>> encryptTable = []
>>> for i in xrange(97,123):
temp = chr(i)
if temp in vowel:
encryptTable.append(vowel[vowel.find(temp)+1])
else:
encryptTable.append(con[con.find(temp)+1])
>>> encryptTable
['e', 'c', 'd', 'f', 'i', 'g', 'h', 'j', 'o', 'k', 'l', 'm', 'n', 'p', 'u', 'q', 'r', 's', 't', 'v', 'a', 'w', 'x', 'y', 'z', 'b']
And then replace the content:
>>> plain = "helloworld"
>>> encrypted = "".join([encryptTable[ord(i)-ord('a')] for i in plain])
>>> encrypted
'jimmuxusmf'
def encrypt(s):
vowels = 'aeiou'
vowelReps = dict(zip(vowels, vowels[1:]+vowels[0]))
cons = 'bcdfghjklmnpqrstvwxyz'
consReps = dict(zip(cons, cons[1:]+cons[0]))
answer = []
for char in s:
if char.lower() in vowelReps:
answer.append(vowelReps[char.lower()]
else:
answer.append(consReps[char.lower()]
if char.isupper():
answer[-1] = answer[-1].upper()
return ''.join(answer)
You have multiple problems here:
for eo in ... would replace the eo argument; except
t isn't defined, so will give a NameError;
res= is a SyntaxError; and
Even if all of the above was fixed, return res will happen on the first character, as it is indented too far.
Instead, you could do the following:
def encrypt(eo):
vowels = "aeiou"
for index, vowel in enumerate(vowels): # iterate through the five vowels
new_v = vowels[(index + 1) % len(vowels)] # determine replacement
eo = eo.replace(vowel, new_v) # do replacement
You can then do the same thing for the consonants, then return eo (which should be indented to the same level as vowels = ...!).
Note:
the use of % to keep the index into vowels within the appropriate range; and
the use of enumerate to get both the character vowel from the string vowels and its index within that string.
Alternatively, and more efficiently:
build a dictionary mapping character in to character out;
build a list of replacement characters using the input eo and the dict; and
str.join the output characters together and return it.

Categories

Resources