简体   繁体   中英

Indexing lines of text in a .txt file

Say I have a .txt file. The file contains alternating lines of words and numbers:

Mary
156
Sue
160
Jenn
154

I want to put these alternating lines into a dictionary like ('Mary': 156). My first thought was to use a for-loop with the % operator but I'm still stuck on actual implementation. Is it possible to index lines in a text file? What my train of thought is so far:

for i in range(len(text)):
    if i%2 == 0

Edit2: can do it even more simply:

with open("data.txt") as inf:
    data = {name.strip():int(num) for name,num in zip(inf, inf))

returns

{'Mary': 156, 'Sue': 160, 'Jenn': 154}

Edit3: (response to comment):

"Mary,Jade,Jenn\n".split(',', 1)

returns

["Mary", "Jade,Jenn\n"]

So if you only want a string up to the first comma, you can do

name = in_string.split(',', 1)[0]    # => "Mary"

You could do it like this

with open("data.txt") as data:
    for line in data:
        name = line.strip()
        number = data.readline()
        print name
        print number

How about?

for i in range(0, len(text), 2)

But no need for that really as you can load it with simple:

s = """Mary
156
Sue
160
Jenn
154"""

lines = s.splitlines()
lines = zip(*[iter(lines)]*2)
d = dict(lines)

print d

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