可以使用BeautifulSoup或Python中的regex解析这个半结构化文本文件

时间:2016-01-23 17:09:51

标签: python regex parsing beautifulsoup

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

file.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

有可能用美丽的汤或某种正则表达式吗?

2 个答案:

答案 0 :(得分:7)

我认为最简单的方法就是按first->data = new_node; 分割。

,

with open('file.txt') as f: for line in f: print(line.split(',', 1)[0]) 提供maxsplit参数在这里是可选的,但更有效率,因为您只需要拆分一次。

答案 1 :(得分:1)

BeautifulSoup是一个HTML解析器 - 因为你的文件没有HTML,所以它不会做任何事情。

这是一个正则表达式,它会找到任何域名.com,并忽略其余的域名:

(.+\.com)

所以,要在Python中实现它..

tester = re.compile(r'(.+\.com)')
links = tester.match(linefromfile)