简体   繁体   中英

How to use readlines to read from file and return the abbreviation of item

file looks like this:

BURGER KING
BRG
MCDONALDS
MCDNLDS
WENDYS
WNDY

Example:

food('abbreviations.txt')

Enter a fast food place: McDonalds

Abbreviation: MCDNLDS

Enter a fast food place:

Thank you!

so far:

infile = open(filename, 'r')

l = infile.readlines()

infile.close()

but I don't know what to do after readlines

I shouldn't be doing this, but I found the exercise funny. So here we go:

lines = [i.strip() for i in l if i.strip()]
abbrev = dict(zip(lines[0::2], lines[1::2]))

Then abbrev is a dictionary/mapping where you obtain abbreviatons by looking up whole names as keys.

If you want to understand the statement I suggest you try each piece separately in an interactive python shell.

Edit for lazy StackOverflow readers

Here's the interactive session example, with some additional suggestions:

>>> infile = open("abbreviations.txt", "r")
>>> lines = [l.strip() for l in infile]
>>> lines
['BURGER KING', '', 'BRG', '', 'MCDONALDS', '', 'MCDNLDS', '', 'WENDYS', '', 'WNDY']
>>> lines[0::4]
['BURGER KING', 'MCDONALDS', 'WENDYS']
>>> lines[2::4]
['BRG', 'MCDNLDS', 'WNDY']
>>> zip(lines[0::4], lines[2::4])
[('BURGER KING', 'BRG'), ('MCDONALDS', 'MCDNLDS'), ('WENDYS', 'WNDY')]
>>> abbrev = dict(zip(lines[0::4], lines[2::4]))
>>> abbrev
{'MCDONALDS': 'MCDNLDS', 'WENDYS': 'WNDY', 'BURGER KING': 'BRG'}
>>> abbrev["WENDYS"]
'WNDY'

You could read lines in pairs and make them keys and values, respectively, to add to a dictionary. Then get user input (in a loop) and look up the entered string in that dict.

Here's a start:

name_map = {}
last_line = False
for line in file.readlines():
    line = line.strip()

    if not line:
        # Blank line
        continue

    if not last_line:
        last_line = line
    else:
        name_map[last_line] = line
        last_line = False

Really you should be using something like JSON .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM