Skip to main content
 首页 » 编程设计

python之可以在 Python 中使用 BeautifulSoup 或正则表达式解析此半结构化文本文件

2025年05月04日29jillzhang

我如何解析我拥有的这个文本文件并仅提取每行中的第一个值?

文件.txt:

http://google.com,username2,mypassword1

http://yahoo.com,username3,mypassword2

http://ebay.com,username4,mypassword7

预期输出:

http://google.com 
http://yahoo.com 
http://ebay.com 

是否可以用漂亮的汤或某种正则表达式来做?

请您参考如下方法:

我认为最简单的方法就是按,拆分。

with open('file.txt') as f: 
    for line in f: 
        print(line.split(',', 1)[0]) 

为 str.split 提供 maxsplit 参数在这里是可选的,但效率更高一些,因为您只需要拆分一次。