Skip to main content
 首页 » 编程设计

python之在 Python 中搜索 TXT 文件

2025年05月04日17oomusou

我是一名新程序员,我们正在从事一个研究生英语项目,我们正在尝试解析一个巨大的字典文本文件 (500 MB)。该文件设置有类似 html 的标签。我有 179 个作者标签,​​例如。莎士比亚的“[A>]Shakes.[/A]”,我需要做的是找到每个标签的每次出现,然后在行上写下该标签和后面的内容,直到我到达“[/W]”。

我的问题是 readlines() 给我一个内存错误(我假设是因为文件太大)而且我已经能够找到匹配项(但只有一次)并且无法让它看过去第一场比赛。任何人都可以提供的任何帮助将不胜感激。

文本文件中没有我认为导致问题的新行。这个问题已经解决了。我想我会包含有效的代码:

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 

请您参考如下方法:

打开文件后,像这样遍历行:

input_file = open('huge_file.txt', 'r') 
for input_line in input_file: 
   # process the line however you need - consider learning some basic regular expressions 

这将使您可以根据需要逐行读取文件,而不是一次将其全部加载到内存中,从而轻松处理文件