Python 获取单词的上下文

Python 获取单词的上下文,python,Python,我正在处理一个非常大的文本文件(大约3.77GB),试图提取某个特定单词出现的所有句子,并将其写入文本文件 因此,大文本文件只是多行文本: line 1 text .... line 2 text .... 我还从文本文件中提取了唯一的单词列表,希望提取每个单词出现的所有句子,并写出与该单词相关的上下文。理想情况下,输出文件的格式为 word1 \t sentence 1\n sentence 2\n sentence N\n word2 \t sentence 1\n sente

我正在处理一个非常大的文本文件(大约3.77GB),试图提取某个特定单词出现的所有句子,并将其写入文本文件

因此,大文本文件只是多行文本:

line 1 text ....
line 2 text ....
我还从文本文件中提取了唯一的单词列表,希望提取每个单词出现的所有句子,并写出与该单词相关的上下文。理想情况下,输出文件的格式为

word1 \t sentence 1\n   sentence 2\n  sentence N\n 
word2 \t sentence 1\n   sentence 2\n   sentence M\n
我目前的代码是这样的:

fout=open('word_context_3000_4000(4).txt','a')

for x in unique_word[3000:4000]:
    fout.write('\n'+x+'\t')
    fin=open('corpus2.txt')
    for line in fin:
            if x in line.strip().split():
                    fout.write(line)
            else:
                    pass
fout.close()
因为唯一的单词列表很大,所以我逐块处理单词列表。但是,不知何故,代码未能获取所有单词的上下文,只返回唯一单词列表中前几百个单词的上下文

以前有没有人研究过类似的问题?顺便说一句,我正在使用python


非常感谢。

第一个问题,您永远不会关闭
fin

也许你应该试试这样:

fout=open('word_context_3000_4000(4).txt','a')

fin=open('corpus2.txt')
for x in unique_word[3000:4000]:
    fout.write('\n'+x+'\t')
    fin.seek(0)     # go to the begining of the file
    for line in fin:
            if x in line.strip().split():
                    fout.write(line)
            else:
                    pass
fout.close()
fin.close()

第一个问题,您从未关闭
fin

也许你应该试试这样:

fout=open('word_context_3000_4000(4).txt','a')

fin=open('corpus2.txt')
for x in unique_word[3000:4000]:
    fout.write('\n'+x+'\t')
    fin.seek(0)     # go to the begining of the file
    for line in fin:
            if x in line.strip().split():
                    fout.write(line)
            else:
                    pass
fout.close()
fin.close()