-4

I am trying to take a value from user and read a list of words from a Passwords.txt file, and shift each letter to right by value

•def shift():
    value=eval(input("Please enter the value here."))
    file = open("Passwords.txt","w")
    with open ("word-text.txt","r") as m:
        for line in m:
            line=line.strip()
            print (line)
            newString = ""
            for char in line:
                char_int=ord(char)
                t=char_int+value
                if t==124:
                    t = t-27
                charme= chr(t)
                print (char,">>",charme)
                newString += charme
            file.writelines(line+" "+newString+"\n")
  • 1
    Here right shifting a letter by `k` means next `k`th letter. For example: `h` becomes `j` when shifted right by 2 – mshsayem Oct 27 '13 at 08:12
  • 3
    Stack overflow is a place where to ask for help when you have some problem. Not to get your work done for free. So **try to do it yourself**. If you get stuck at some point come back, show us what have you done and you will get help. Btw: if you are new to programming, the best thing to do is to program! – Francesco Montesano Oct 27 '13 at 08:31

3 Answers3

1

you don't have to convert to ascii, you can just use maketrans function

def shift_string(text, shift):
    intab='abcdefghijklmnopqrstuvwxyz'
    outab=intab[shift:]+intab[:shift]
    return maketrans(intab, outab)
yemu
  • 26,249
  • 10
  • 32
  • 29
  • 1
    You should use `string.maketrans` instead of `maketrans`. And also you could do `intab = string.printable` – JadedTuna Oct 27 '13 at 10:15
0

The heavy lifting is doing the word conversion, so I've done that - you can do the rest as it's very trivial. :)

This works by converting each character into a numeric representation and correcting for circular performance (i.e. Z shifted by 2 will output B).

def limits_correction(character, distance, start, end):
    char = character
    if char >= start and char < end:
        if char + distance >= end:
            char = char + distance - 26
        else:
            char = char + distance
    return char


def modify_string(string, distance):
    ords = [ord(c) for c in string]

    corrected_distance = 0
    if distance > 26:
        corrected_distance = distance % 26
    elif distance > 0 and distance <= 26:
        corrected_distance = distance

    lower_start = 97
    lower_end = lower_start + 26
    upper_start = 65
    upper_end = upper_start + 26

    shifted_string = []

    for char in ords:
        if char >= lower_start and char < lower_end:
            char = limits_correction(char, corrected_distance, lower_start, lower_end)
        elif char >= upper_start and char < upper_end:
            char = limits_correction(char, corrected_distance, upper_start, upper_end)

        shifted_string.append(chr(char))

    return ''.join(shifted_string)

This also works for uppercase and lowercase for any integer shift number (read as from 0 to very large).

REFERENCE:

http://www.asciitable.com/

jrd1
  • 10,358
  • 4
  • 34
  • 51
  • 2
    Try not to convert stack overflow into a homework writing service; for clear homework assignments, its better to provide _hints_. – Burhan Khalid Oct 27 '13 at 09:11
  • 1
    @BurhanKhalid: I don't want that for SO, but given the design of the system (i.e. higher reputation gives one access to more tools), if one wants such access, this happens: http://meta.stackexchange.com/a/33407. Plus, it's good to help someone here and there, *and* sometimes by attempting something, you learn as well. :) Thanks for your feedback, though - I will keep it it mind in future. :) – jrd1 Oct 27 '13 at 09:48
  • 1
    @user2924427: if by built-in you mean *functions defined within Python*, then yes. If you mean by the functions I created and used, then I only created those to simplify the abstraction of the problem. Simpler code is more easily understood when read. And, by `distance`, your conjecture is correct: it is the number of letters by which to shift to the right (i.e. positively): e.g.: `a` shifted by `2` is `c`. As you desired. And, you're most welcome. – jrd1 Oct 27 '13 at 20:06
0

You need to do the assignment yourself (or there is no point in learning to program) and if you don't understand the question, you should ask your teacher for clarification.

That said, shifting is quite simple in principle. You can do it by hand. If you have a letter, say A, shifting it by 1 (key = 1) would transform it into B. In the assignment you shift by 2 places, so A would become C, B (in the original word) would be become D and so on. You have to be a bit careful about the end of the alphabet. When shifting by 1, Z becomes A. When shifting by 2, Y becomes A and Z becomes B.

So in your example, HELLO becomes JGNNQ because when shifting 2 places:

H => J

E => G

L => N

O => Q

(Note: I'm using uppercase for readability but your assignment seems to be about working on lowercase characters. I'm assuming you're only asked to handle lowercase.)

How do you do this? Check out the links you were given. Basically ord() transforms a character into an integer and chr() transforms one such integer into a character. It's based on the way characters are represented as numbers in the computer. So for a given character, if you transform it into its ord(), you can add the key to shift it and then transform it back into a character with chr().

For wrapping from Y and Z to A and B, you can use the modulus operator (%) for this but be careful, it's a bit fiddly (you need to calculate the difference between the ord of your character and the ord of 'a', apply % 26 (which gives you a number between 0 and 25), then add it to ord('a) to have the correct ord). If it's too complicated, just do it with a couple of IFs.

I'd advise to start with a small program that takes input from the user and prints the output to check that it's working correctly. You won't need the input and print in the final version but it will help you to test that your shifting code works correctly.

Then you have the part about reading from a file and writing to a file. Your assignment doesn't ask the user for input, instead it reads from a file. Your line with open ("word-text.txt","r") as f: looks fine, this should give you the file handle you need to read the data. You can read the data with f.read() and assign it to a variable. I'm not sure what you've been taught, but I'd split the string into words with <string>.split() which creates a list of strings (your words).

Then for each word, you use the code you wrote previously to shift the string and you can just write both the original word and the shifted word into the output file. The simplest would probably be to start by opening the output file (in writing mode) and do both the shifting and the writing in one go by looping on the list.

user2465896
  • 183
  • 8
  • That's exactly what I needed, I needed an explanation, not someone doing the whole code for me, there is no point for taking the class then, but, I am not really sure, why am I struggling at some point, when the teacher asks me to do some functions, its like, I do not know what to use sometimes, is that a common thing for new programmers? –  Oct 27 '13 at 20:10
  • 1
    @user2924427: Not knowing which function to use is not uncommon for beginners - that's where experience and learning comes into play. The takeaway point is to keep practicing and reading - that's how one gets better. – jrd1 Oct 27 '13 at 20:17
  • I will keep this in mind, than you so much for the great explanation that you gave me up there :) –  Oct 27 '13 at 20:29
  • 1
    If my answer was helpful to you, please upvote, I need the rep :) When you have a problem like this with multiple things to do, break it into smaller, more manageable steps. Don't forget you can experiment with new functions in the python shell, e.g. typing `ord('a')` => you get 97, then `chr(97)` => you get 'a'. Make sure you understand the problem - ask questions. Get familiar with python's documentation, especially the Standard Library. Most of what you need as a beginner is in Built-in Functions and Built-in Types. – user2465896 Oct 28 '13 at 11:04