【问题标题】:Python | Reformatting each line in a text file consistently蟒蛇 |一致地重新格式化文本文件中的每一行
【发布时间】: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


【解决方案1】:

假设所有的逗号都是单词分隔符。为方便起见,我将用逗号 箭头分隔每一行:

import re

line = 'correct, wrong1, wrong2->wrong3'
terms = re.split(r", *|->", line)
new_line = ", ".join(terms[1:]) + "->" + terms[0]
print(new_line)

你可以把它放回文件读取循环中,对吧?

【讨论】:

  • 我对此做了一些调整。我将附加到我的帖子底部。
  • 很高兴它对你有用!虽然我不确定你为什么说你做了“调整”,但你在文件读写循环中使用了该解决方案,完全按照它的用途。
【解决方案2】:

我建议建立一个列表,而不是假设元素的数量。当您在逗号上拆分时,第一个元素是正确的单词,元素 [1:-1] 是拼写错误,而 [-1] 将是您必须在箭头上拆分的那个。

我认为您还发现 write 需要一个换行符,如 cmets 中所建议的“\n”。

【讨论】:

    猜你喜欢
    • 2015-03-31
    • 1970-01-01
    • 2014-10-01
    • 2019-09-20
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多