从txt文件中提取特定类型的字符串

时间:2013-07-01 11:21:27

标签: python string file python-2.7 extract

我有一个sql文件,其中包含两个名为'email'和'pass'的列字段。 样本部分如下

'vloz54yC7q9p85i2Uwdi', 'zurunet', 'zurunet@hotmail.com', '', '', '', '', '',     'http://www.bnadm.com', '1a36c4e04a065e1840132b64a1b0a2a8', 9, '1186148119', '', '', '', '', '', '', '', '', 0, '', '', 0);
INSERT INTO `nuked_users` VALUES ('avtGdl4zt9woGjXevy3j', '1aflam',    'zaiker_8@hotmail.com', 'zaiker_8@hotmail.com', '', '', '', '', '',    '13530b1a10329459789c8972909dddb4', 1, '1186451181', '', '', '', '', '', '', '', '', 0, '', '', 0);

我想要做的只是提取用户的电子邮件和密码。

为此,我怎样才能在最后用 @ hotmail.com 提取所有字符串。 如果txt文件的名称是foo.txt,

fo = open("foo.txt" , 'r')
listme = fo.readlines()
listme将是该文件中的字符列表,我需要在结尾处仅使用@ hotmail.com过滤掉那些字符串。

1 个答案:

答案 0 :(得分:3)

你可以做这样的事情

with open("foo.txt" , 'r') as foo:
    listme = foo.read()

string =  listme.strip().split(',')
new_string = ''


for words in string:
    if words not in new_string:
        if '@hotmail.com' in words:
            new_string+=words


print new_string

这将打开文件(使用with语句),然后读取它,然后在每个逗号分割大字符串,然后它使用for循环遍历每个字符串,最后一个条件将检查它是否已被使用,如果不是另一个条件挑选出@hotmail.com中的字符串!

输出是:

'zurunet@hotmail.com' 'zaiker_8@hotmail.com'