获取单词的上下文
我正在处理一个非常大的文本文件(大约3.77 GB),想要提取出特定单词出现的所有句子,并将这些句子写入一个文本文件。
这个大文本文件就是很多行文本:
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。
非常感谢。
1 个回答
1
第一个问题是,你从来没有关闭过 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()