繁体   English   中英

读取文本文件的每一行并获取第一个拆分字符串

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM