我如何解析我拥有的这个文本文件并仅提取每行中的第一个值?
文件.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
参数在这里是可选的,但效率更高一些,因为您只需要拆分一次。
关于python - 可以在 Python 中使用 BeautifulSoup 或正则表达式解析此半结构化文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34966355/