【问题标题】:Conditionally merge lines in text file有条件地合并文本文件中的行
【发布时间】:2021-09-02 14:40:42
【问题描述】:

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

同一个单词的所有拼写错误都应该在同一行。

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

misspellings_corpus.txt (sn-p):

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

模板:wrong1, wrong2, wrongN->correct


尝试:

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

【问题讨论】:

  • collections.defaultdict(list) 与您的正确拼写键一起使用,并将每个错误拼写附加为一个值。然后一旦完成,您可以根据需要写出 values() 和 key
  • 我对所需的文字感到困惑。第一行不应该是:I'd, I'd, I'd, I'd,第二行也不应该是:apple, apple
  • @jrd1 目的是用逗号, 分隔拼写错误,然后-> 正确拼写。我会将所需的模板附加到帖子中。
  • @JonSG 我现在在帖子中附加了correct_words 的列表。我会调查collections

标签: python list text slice


【解决方案1】:

将单词的正确拼写存储为字典的键,该字典映射到该单词的一组可能的拼写错误。 dict 旨在让您轻松找到要更正的单词,而 set 旨在避免拼写错误的重复。

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)

【讨论】:

  • 我现在试试这个并报告。谢谢。
  • 有效!打字机。假设,我怎样才能消除一行中重复的 拼写错误
  • 这段代码也应该去掉它们。请注意,我正在从一行中的拼写错误创建一个集合,因此它也不会接受任何重复。
  • 嗯,好的。又是 Tysm。
  • 消除任何类型的重复项的关键是使用集合而不是列表,因为集合是将元素视为属于或不属于它们的事物的结构。然后,当您尝试添加已在集合中的元素时,其状态仍将是“属于该集合”。
【解决方案2】:
lines = []
with open('misspellings_corpus.txt', 'r') as fin:
  lines = fin.readlines()
from collections import defaultdict
my_dict = defaultdict(list)


for line in lines:
    curr_line = line.split("->")[0].replace(" ","")
    if "," in curr_line:
        for curr in curr_line.split(","):
            my_dict[line.split("->")[1].strip()].append(curr)
    else:
        my_dict[line.split("->")[1].strip()].append(curr_line)

for key, values in my_dict.items():
    print(f"{key} -> {', '.join(values)}")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    相关资源
    最近更新 更多