我有一个文本文件,其中包含常见的拼写错误及其更正。
同一单词的所有拼写错误都应位于同一行。
我确实做了一些工作,但不是针对同一个单词的所有拼写错误。
misspellings_corpus.txt
(片段):
I'de->I'd
aple->apple
appl->apple
I'ed, I'ld, Id->I'd
期望:
I'de, I'ed, I'ld, Id->I'd
aple, appl->apple
模板:错误1,错误2,错误N->正确
尝试:
lines = []
with open('/content/drive/MyDrive/Colab Notebooks/misspellings_corpus.txt', 'r') as fin:
lines = fin.readlines()
for this_idx, this_line in enumerate(lines):
for comparison_idx, comparison_line in enumerate(lines):
if this_idx != comparison_idx:
if this_line.split('->')[1].strip() == comparison_line.split('->')[1].strip():
#...
correct_words = [l.split('->')[1].strip() for l in lines]
correct_words
最佳答案
将单词的正确拼写存储为字典的键,该字典映射到该单词的一组可能的拼写错误。该词典旨在让您轻松找到您要更正的单词,该集合旨在避免重复拼写错误。
possible_misspellings = {}
with open('my-file.txt') as file:
for line in file:
misspellings, word = line.split('->')
word = word.strip()
misspellings = set(m.strip() for m in misspellings.split(','))
if word in possible_misspellings:
possible_misspellings[word].update(misspellings)
else:
possible_misspellings[word] = misspellings
然后你可以迭代你的字典
with open('my-new-file.txt', 'w') as file:
for word, misspellings in possible_misspellings.items():
line = ','.join(misspellings) + '->' + word + '\n'
file.write(line)
关于python - 有条件地合并文本文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69032440/