Python在符号@后读取.text和拆分单词

问题描述 投票:0回答:2

我有一个带有电子邮件地址的大型11 GB .txt文件。我想只保存字符串直到@符号相互之间。我的输出只生成第一行。我使用了早期项目的代码。我想将输出保存在不同的.txt文件中。我希望有人可以帮助我。

我的代码:

import re 

def get_html_string(file,start_string,end_string):
    answer="nothing"
    with open(file, 'rb') as open_file: 
        for line in open_file:
            line = line.rstrip()
            if re.search(start_string, line) :
                answer=line
                break
    start=answer.find(start_string)+len(start_string)
    end=answer.find(end_string)
    #print(start,end,answer)
    return answer[start:end]


beginstr=''
end='@'
file='test.txt'
readstring=str(get_html_string(file,beginstr,end))


print readstring
python string split
2个回答
1
投票

你的文件很大(11G)所以你不应该把所有这些字符串保存在内存中。相反,逐行处理文件并在读取下一行之前写入结果。

这应该是有效的:

with open('test.txt', 'r') as input_file:
    with open('result.txt', 'w') as output_file:
       for line in input_file:
            prefix = line.split('@')[0]
            output_file.write(prefix + '\n')

1
投票

如果您的文件如下所示:

[email protected]
[email protected]
[email protected]

你可以用这个:

def get_email_name(file_name):
    with open(file_name) as file:
        lines = file.readlines()
    result = list()
    for line in lines:
        result.append(line.split('@')[0])
    return result

get_email_name('emails.txt')

日期:

['user', 'user2', 'Useruser']
© www.soinside.com 2019 - 2024. All rights reserved.