gpt4 book ai didi

python - python中的大TXT文件解析问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:23:14 25 4
gpt4 key购买 nike

一整天都在想办法解决这个问题。我有一个大文本文件 (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

我几乎没有编程经验,我正试图为我正在进行的诗歌项目弄清楚这一点。非常感谢任何帮助。

最佳答案

  1. 您的逻辑是错误的,因为如果未找到字符串,.find() 将返回 -1,而 -1 是一个真实的值,因此您的代码会认为每一行都有 <A>

  2. 您无需创建新的子字符串即可找到 '</W>' ,因为 .find() 也有一个可选的起始参数。

  3. 这些都不能解释内存不足的原因。你有一台异常小内存的机器吗?

  4. 您确定向我们展示了所有代码吗?

已编辑:好的,现在我认为您的文件中只有一行。

尝试像这样更改您的代码:

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

关于python - python中的大TXT文件解析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6795027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com