简体   繁体   English

如何使用readlines读取文件并返回item的缩写

[英]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. 然后abbrev是一个字典/映射,您可以在其中查找全名作为键来获得abbreviatons。

If you want to understand the statement I suggest you try each piece separately in an interactive python shell. 如果您想了解该语句,建议您在交互式python shell中分别尝试每篇。

Edit for lazy StackOverflow readers 编辑懒惰的StackOverflow阅读器

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 . 确实,您应该使用JSON之类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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