簡體   English   中英

如何使用readlines讀取文件並返回item的縮寫

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

文件看起來像這樣:

BURGER KING
BRG
MCDONALDS
MCDNLDS
WENDYS
WNDY

例:

food('abbreviations.txt')

Enter a fast food place: McDonalds

Abbreviation: MCDNLDS

Enter a fast food place:

Thank you!

至今:

infile = open(filename, 'r')

l = infile.readlines()

infile.close()

但我不知道讀完后該怎么辦

我不應該這樣做,但是我發現這項運動很有趣。 所以我們開始:

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

然后abbrev是一個字典/映射,您可以在其中查找全名作為鍵來獲得abbreviatons。

如果您想了解該語句,建議您在交互式python shell中分別嘗試每篇。

編輯懶惰的StackOverflow閱讀器

這是交互式會話示例,其中包含一些其他建議:

>>> 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'

您可以成對讀取行,並分別使它們成為鍵和值,以添加到字典中。 然后獲取用戶輸入(循環)並在該字典中查找輸入的字符串。

這是一個開始:

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

確實,您應該使用JSON之類的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM