将字典输出为文本文件的一种方法是作为JSON 字符串:
import json
lexnorm = {'nonstandard1': 'standard1', 'nonstandard2': 'standard2', 'nonstandard3': 'standard3'} # etc.
with open('lexnorm.txt', 'w') as f:
json.dump(lexnorm, f)
请参阅我对您原件的评论。我只是在猜测您要做什么:
import json, re
with open('lexnorm.txt') as f:
lexnorm = json.load(f) # read back lexnorm dictionary
with open("corpus.txt", 'r', encoding='utf8') as main, open('new_corpus.txt', 'w') as new_main:
for line in main:
words = re.split(r'[^a-zA-z]+', line)
for word in words:
if word in lexnorm:
line = line.replace(word, lexnorm[word])
new_main.write(line)
上述程序逐行读取corpus.txt文件并尝试智能地将行拆分为单词。在单个空间上拆分是不够的。考虑以下句子:
'"The fox\'s foot grazed the sleeping dog, waking it."'
在单个空间上的标准分割产生:
['"The', "fox's", 'foot', 'grazed', 'the', 'sleeping', 'dog,', 'waking', 'it."']
您将永远无法匹配 The、fox、dog 或 it。
有几种方法可以处理它。我正在拆分一个或多个非字母字符。如果lexnorm 中的单词由 a-z 以外的字符组成,则可能需要“tweeked”:
re.split(r'[^a-zA-z]+', '"The fox\'s foot grazed the sleeping dog, waking it."')
产量:
['', 'The', 'fox', 's', 'foot', 'grazed', 'the', 'sleeping', 'dog', 'waking', 'it', '']
将行拆分为单词后,将在lexnorm 字典中查找每个单词,如果找到,则在原始行中对该单词进行简单替换。最后,该行和对该行所做的任何替换都将写入一个新文件。然后您可以删除旧文件并重命名新文件。
想想如果首先将它们转换为小写,你将如何处理匹配的单词。
更新(主要优化)
由于一个文件中很可能有很多重复的单词,一个优化是对每个唯一的单词处理一次,如果文件不是太大而无法读入内存的情况下可以这样做:
import json, re
with open('lexnorm.txt') as f:
lexnorm = json.load(f) # read back lexnorm dictionary
with open("corpus.txt", 'r', encoding='utf8') as main:
text = main.read()
word_set = set(re.split(r'[^a-zA-z]+', text))
for word in word_set:
if word in lexnorm:
text = text.replace(word, lexnorm[word])
with open("corpus.txt", 'w', encoding='utf8') as main:
main.write(text)
这里将整个文件读入text,分割成单词,然后将单词添加到集合word_set中,保证单词的唯一性。然后在整个文本中查找并替换word_set 中的每个单词,并将整个文本重写回原始文件。