-2

Code:

trans_file = open("textabbv.txt", "r")
def text_translate(user_input):
    user_input = input("Please enter your text: ")  
    textdict = {}
    for line in trans_file:
        readline(line)
        line = line.split(":")
        line = line.strip('\n')

Contents of textabbv.txt:

r:
are
y:
why
u:
you
ttyl:
talk to you later
l8:
late
brb:
be right back
lol:
laughing out loud
bbl:
be back later
tl;dr:
too long; didn't read
rofl:
rolling on floor laughing
gtg:
got to go
cya:
see you
cuzz:
because
bff:
best friend forever
bffs:
best friends forever
idk:
I don't know
sup:
what's up?
omg:
oh my gosh
nbd:
no big deal
tisnf:
this is not fair
nw:
no way!
rus:
are you serious?
myob:
mind your own business
njoy:
enjoy
nter:
enter
1ce:
once
aka:
also known as
afk:
away from keyboard
jk:
just kidding
asap:
as soon as possible
app:
application
atm:
at the moment
b4:
before
fyi:
for your information
bday:
birthday
k:
okay
msg:
message
np:
no problem
pic:
picture
plz:
please
sry: sorry
dunno:
don't know
@:
at
wut:
what
wuts:
what's

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
AmyLee
  • 21
  • 3
  • 1
    I realize you're also new to SO, but this is a bad question - that's why it's getting downvotes. Please post a small portion of your text file and your source code directly into your question instead of linking to it on a third-party site in image format. Anyone trying to test your code would have to manually type it all for no good reason. – Natsukane Jun 26 '16 at 16:36
  • I'm sorry I will do that – AmyLee Jun 26 '16 at 16:57
  • Is the last line of your txt file `brb:`? – RoadRunner Jun 26 '16 at 17:00
  • Hi everyone, I am writing a function with def, so can we please refrain from using with? – AmyLee Jun 26 '16 at 17:29
  • @AmyLee Don't change your question to a different one, after you've got an answer to the initial version. – BartoszKP Jun 26 '16 at 17:37
  • @AmyLee Try the solutions you got here, and then you can spend some effort to change them removing the `with` keyword if you don't like it, or (better) try to understand it. SO (and the internet) is full of explanations of this keyword. – BartoszKP Jun 26 '16 at 17:39
  • The with statement will automatically close your file when the block of code is completed. If you don't want to use it, don't forget to close your file when you are done with it. – joel goldstick Jun 26 '16 at 17:39
  • Thank you to so much to everyone who answered my question, I will take these comments and continue on my code. – AmyLee Jun 26 '16 at 19:34
  • @AmyLee Cheers and good luck! If you're stuck again, and can't find an answer amongst the existing posts on SO, you can always post another question :-) – BartoszKP Jun 26 '16 at 22:00

3 Answers3

1

You can try this:

abbvs = []
with open("textabbv.txt") as file:
    for line in file:
        line = line.strip().strip(":")
        abbvs.append(line)

pairs = dict([tuple(abbvs[i:i+2]) for i in range(0, len(abbvs), 2)])

print(pairs)

Output:

{'l8': 'late', 'r': 'are', 'ttyl': 'talk to you later', 'u': 'you', 'y': 'why'}

If you don't want to use with, just do this:

abbvs = []
for line in open("textabbv.txt").readlines():
    line = line.strip().strip(":")
    abbvs.append(line)

pairs = dict([tuple(abbvs[i:i+2]) for i in range(0, len(abbvs), 2)])
print(pairs)

Can even do this to handle uneven lines in files:

try:
    abbvs = []
    with open("textabbv.txt") as file:
        for line in file:
            line = line.strip().strip(":")
            abbvs.append(line)

    pairs = dict([tuple(abbvs[i:i+2]) for i in range(0, len(abbvs), 2)])

    print(pairs)

except ValueError:
    print("Uneven number of lines in txt file found")
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
  • I get this error... builtins.ValueError: dictionary update sequence element #0 has length 1; 2 is required – AmyLee Jun 26 '16 at 16:51
  • @Amina This most probably means an error in the text file (most of time there's something wrong with the last entry). – BartoszKP Jun 26 '16 at 16:53
  • Yeah I made another text file with the picture you posted, which was all I could see. Can you show the whole picture of it @Amina? – RoadRunner Jun 26 '16 at 16:55
  • I will post a picture – AmyLee Jun 26 '16 at 16:56
  • Yeah Just post the whole thing, so we can see exactly what's in there. – RoadRunner Jun 26 '16 at 17:00
  • Yeah this should work if for every key, there is a value. – RoadRunner Jun 26 '16 at 17:10
  • I posted everything including my code and the .txt file so you can see everything – AmyLee Jun 26 '16 at 17:12
  • Yeah there was something wrong with your text file, One line had `sry: sorry`, which will make the code not work as there will be an uneven number of lines. Make sure that line is separated, and then run the code again, it should work. – RoadRunner Jun 26 '16 at 17:16
  • It worked ! Thank you so much...I am not familiar with the "with" that you have in your code, what purpose does it serve? – AmyLee Jun 26 '16 at 17:24
  • Yeah `with` just makes sure that your file will get closed, it stops you from going `file.close()` everytime you want to close a file. Just a fool proof method of handling files. A good explanation can be found here https://docs.python.org/2/tutorial/inputoutput.html – RoadRunner Jun 26 '16 at 17:29
  • @AmyLee if you liked this answer then mark it as correct :) – RoadRunner Jun 27 '16 at 03:56
  • Sorry @RoadRunner I liked it just now! :) – AmyLee Jun 27 '16 at 18:31
  • Thanks @AmyLee, I hoped this help a bit. If you still need some more help just let me know :) – RoadRunner Jun 28 '16 at 05:14
0

Here you have a quick oneliner:

>>> f = open(r"c:/tests/test.txt", "r")
>>> xlines = iter(f.readlines())
>>> {k.rstrip("\n").rstrip(":"):v.strip("\n") for k, v in zip(xlines,xlines)}
{'pic': 'picture', 'np': 'no problem', 'aka': 'also known as', 'k': 'okay', 'nw': 'no way!', 'sry: sorry': 'dunno:', 'myob': 'mind your own business', 'bffs': 'best friends forever', 'afk': 'away from keyboard', 'tisnf': 'this is not fair', '1ce': 'once', 'jk': 'just kidding', 'tl;dr': "too long; didn't read", 'ttyl': 'talk to you later', 'bff': 'best friend forever', 'asap': 'as soon as possible', 'njoy': 'enjoy', 'nter': 'enter', 'r': 'are', 'atm': 'at the moment', 'what': 'wuts:', 'gtg': 'got to go', 'cuzz': 'because', 'cya': 'see you', 'rofl': 'rolling on floor laughing', 'app': 'application', 'u': 'you', 'y': 'why', 'lol': 'laughing out loud', 'nbd': 'no big deal', 'brb': 'be right back', 'bbl': 'be back later', 'b4': 'before', 'omg': 'oh my gosh', 'fyi': 'for your information', 'at': 'wut:', 'rus': 'are you serious?', 'l8': 'late', 'msg': 'message', 'sup': "what's up?", "don't know": '@:', 'plz': 'please', 'idk': "I don't know", 'bday': 'birthday'}
Netwave
  • 40,134
  • 6
  • 50
  • 93
-1

Your problem basically boils down to reading two lines at a time, which has been answered here. So the solution for your file is:

import pprint

def text_translate():
    result = {}
    with open('textabbv.txt', 'r') as f:
        for line in f:
            key = line.strip().strip(':')
            value = f.next().strip()
            result[key] = value
    return result

abbrvs = text_translate() 
pprint.pprint(abbrvs)

with next(f) instead of next for Python 3.

Note that if there is odd number of lines in the file, f.next() will raise a StopIteration exception, which should be handled explicitly in this case.

Community
  • 1
  • 1
BartoszKP
  • 34,786
  • 15
  • 102
  • 130