![](/img/trans.png)
[英]Read each line of a text file and then split each line by spaces in python
[英]Read each line of a text file and get the first split string
我想從我的python代碼中讀取一個文本文件link123.txt 。 文本文件包含3行。
www.link1.com | linkname1
www.link2.com | linkname2
www.link3.com | linkname3
我需要將“target”變量和第二部分(鏈接名稱)中行的第一部分(url)分配給“name”變量(以供進一步使用)。
到目前為止代碼:
f = open("link123.txt")
target = [url.strip() for url in f.readlines()]
f.close()
我的問題是如何從一行(“|”)得到兩個值。任何指導都將非常感激。
您可以使用str.split
按分隔符拆分字符串:
>>> 'www.link1.com | linkname1'.split(' | ')
['www.link1.com', 'linkname1']
然后,使用iterable-unpacking(或多個賦值)來保存變量:
>>> target, name = 'www.link1.com | linkname1'.split(' | ')
>>> target
'www.link1.com'
>>> name
'linkname1'
with open("link123.txt") as f:
for line in f:
target, name = line.strip().split(' | ')
# Do something with `target`, `name`
注意:迭代文件對象將產生行。 您不需要使用file.readlines()
返回所有行的列表,除非您需要一次所有行。
UPDATE
如果你想要目標,名稱列表,你可以使用zip
:
>>> rows = [['link1', 'name1'], ['link2', 'name2'], ['link3', 'name3']]
>>> zip(*rows)
[('link1', 'link2', 'link3'), ('name1', 'name2', 'name3')]
# In Python 3.x, zip will return `zip` object instead of list.
with open("link123.txt") as f:
targets, names = zip(*[line.strip().split(' | ') for line in f])
# targets, names = map(list, zip(...)) # if you want lists isntead of tuples
代替
target = [url.strip() for url in f.readlines()]
采用
pairs = [line.strip().split(' | ') for line in f.readlines()]
target = [pair[0] for pair in pairs]
name = [pair[1] for pair in pairs]
您是否需要不同變量中的所有名稱和所有目標,例如:
In [1]:
with open("link123.txt") as f:
targets, names = zip(*[url.strip().split(' | ') for url in f])
targets, names
Out[1]:
(('www.link1.com', 'www.link2.com', 'www.link3.com'),
('linkname1', 'linkname2', 'linkname3'))
但你可能想考慮把它們放在一個字典中:
In [2]
with open("link123.txt") as f:
data = [dict(zip(['target', 'name'], url.strip().split(' | '))) for url in f]
data
Out[2]:
[{'name': 'linkname1', 'target': 'www.link1.com'},
{'name': 'linkname2', 'target': 'www.link2.com'},
{'name': 'linkname3', 'target': 'www.link3.com'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.