[英]Indexing lines of text in a .txt file
Say I have a .txt file. 说我有一个.txt文件。 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). 我想将这些交替的行放入字典中,例如('Mary':156)。 My first thought was to use a for-loop with the % operator but I'm still stuck on actual implementation.
我的第一个想法是使用%运算符使用for循环,但我仍然停留在实际实现上。 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: Edit2:可以更简单地做到这一点:
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): Edit3 :(回复评论):
"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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.