python - 有条件地合并文本文件中的行

标签 python list text slice

我有一个文本文件,其中包含常见的拼写错误及其更正。

同一单词的所有拼写错误都应位于同一行。

我确实做了一些工作,但不是针对同一个单词的所有拼写错误。

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/

相关文章:

python - gaierror [Errno 8] 当使用 Django python 和 gmail 发送邮件时

c# - 获取可用(语言)resx 文件的列表

c# - WPF - 如何在 ViewModel 之间共享集合的单个实例?

jquery - 使用 jQuery 动态更改段落文本?

python - Elasticsearch Python客户端索引JSON

python - 从 Python 日期/时间获取 "2:35pm"而不是 "02:35PM"?

python - dataframe to dict 使得一列是键,另一列是值

r - 列表中每个数据框的行数

delphi - 在 Delphi XE2 中将 Windows 图元文件转换为位图时文本模糊

python - Python 中的文本冒险问题