【发布时间】:2021-10-31 23:17:28
【问题描述】:
我已经制作了自己的语料库,包含拼写错误的单词。
misspellings_corpus.txt:
English, enlist->Enlish
Hallowe'en, Halloween->Hallowean
我的格式有问题。值得庆幸的是,它至少是一致的。
当前格式:
correct, wrong1, wrong2->wrong3
所需格式:
wrong1,wrong2,wrong3->correct
-
wrong<N>的顺序无关紧要, - 每行可能有任意数量的
wrong<N>字(用逗号分隔:,), - 每行只有 1 个
correct字(应该在->的右侧)。
尝试失败:
with open('misspellings_corpus.txt') as oldfile, open('new.txt', 'w') as newfile:
for line in oldfile:
correct = line.split(', ')[0].strip()
print(correct)
W = line.split(', ')[1].strip()
print(W)
wrong_1 = W.split('->')[0] # however, there might be loads of wrong words
wrong_2 = W.split('->')[1]
newfile.write(wrong_1 + ', ' + wrong_2 + '->' + correct)
输出new.txt(不工作):
enlist, Enlish->EnglishHalloween, Hallowean->Hallowe'en
解决方案:(灵感来自@alexis)
with open('misspellings_corpus.txt') as oldfile, open('new.txt', 'w') as newfile:
for line in oldfile:
#line = 'correct, wrong1, wrong2->wrong3'
line = line.strip()
terms = re.split(r", *|->", line)
newfile.write(",".join(terms[1:]) + "->" + terms[0] + '\n')
输出new.txt:
enlist,Enlish->English
Halloween,Hallowean->Hallowe'en
【问题讨论】:
-
newfile.write(wrong_1 + ', ' + wrong_2 + '->' + correct+"\n")? -
如何判断“enlist”是拼写错误而不是单独的单词?
-
@Sujay 所以我的部分问题是我在一行中有任意数量的“错误”单词。所以我不能确定地说在
write()行中有有限数量的变量对象。 :( -
@AzatIbrakov 这只是一个更大文件的示例。即使给定的例子对我来说也足够了。
标签: python python-3.x list text slice