0

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
4

3 回答 3

9

Edit2:可以更简单地做到这一点:

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

返回

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

编辑3:(回复评论):

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

返回

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

所以如果你只想要一个字符串到第一个逗号,你可以这样做

name = in_string.split(',', 1)[0]    # => "Mary"
于 2012-06-01T21:19:34.457 回答
0

你可以这样做

with open("data.txt") as data:
    for line in data:
        name = line.strip()
        number = data.readline()
        print name
        print number
于 2012-06-01T21:18:47.183 回答
0

怎么样?

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

但实际上不需要这样做,因为您可以通过简单的方式加载它:

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

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

print d
于 2012-06-01T21:19:00.587 回答