Python中的大TXT文件解析问题

一直试图想出这一整天.我有一个大文本文件(546 MB),我试图在
python中解析,寻找开放标签和关闭标签之间的文本,我不断得到内存问题.在这个板上的好人的帮助下,这是我到目前为止所拥有的.

answer = ''
output_file = open('/Users/Desktop/Poetrylist.txt','w')

with open('/Users/Desktop/2e.txt','r') as open_file:
    for each_line in open_file:
        if each_line.find('<A>'):
            start_position = each_line.find('<A>')
            start_position = start_position + 3
            end_position = each_line[start_position:].find('</W>')

            answer = each_line[start_position:end_position] + '\n'
            output_file.write(answer)

output_file.close()

我收到此错误消息:

Traceback (most recent call last):
  File "C:\Users\Adam\Desktop\OEDsearch3.py", line 9, in <module>
    end_position = each_line[start_position:].find('</W>')
MemoryError

我几乎没有任何编程经验,我正在努力想出这个我正在研究的诗歌项目.任何帮助是极大的赞赏.

最佳答案 >你的逻辑是错误的,因为.find()如果找不到字符串则返回-1,-1是真值,所以你的代码会认为每一行都有< A>在里面.

>您不需要创建新的子字符串来查找’< / W>‘,因为.find()也有一个可选的start参数.

>这些都没有解释为什么你的内存不足.你有一台非常小的内存机吗?

>您确定要向我们展示所有代码吗?

编辑:好的,现在我认为你的文件只有一行.

尝试更改您的代码,如下所示:

with open('/Users/Desktop/Poetrylist.txt','w') as output_file:
    with open('/Users/Desktop/2e.txt','r') as open_file:
        the_whole_file = open_file.read()
        start_position = 0
        while True:
            start_position = the_whole_file.find('<A>', start_position)
            if start_position < 0:
                break
            start_position += 3
            end_position = the_whole_file.find('</W>', start_position)
            output_file.write(the_whole_file[start_position:end_position])
            output_file.write("\n")    
            start_position = end_position + 4
点赞