在替换文本文件中的单词时保持格式化

时间:2016-03-10 19:36:05

标签: python-3.x

我写了一个简短的程序,它通过一个文本文件,并用拼写的单词替换文件中的缩写。以下是我的代码:

acronyms = {'USA': 'United States of America', 'UK': 'United Kingdom'}

paper = "Emails.txt"

with open(paper) as main:
    words = main.read().split('\s')

text = ' '.join(acronyms.get(y, y) for y in words)

paper = paper.rstrip(".txt")
new_name = ''.join([paper,"_clarified.txt"]) 

with open(new_name, 'w') as f:
    for word in text:
         f.write(word)

我的问题是我无法弄清楚如何完成任务并维护文本文件的格式。我甚至不确定现在的问题是什么 - 如果我使用words = main.read().split('\s')没有替换任何缩写,而如果我使用words = main.read().split()则完美无缺。我很欣赏有关此事的任何指导,即使它只是指向正确的方向。提前谢谢。

1 个答案:

答案 0 :(得分:2)

问题是/s实际上不会返回任何内容,并且拆分所有空白会丢弃您拆分的空白类型。所以转过头来做的就是:

>>> original_text = "Go USA\n Hail UK\n"
>>> acronyms = {"USA": "America", "UK": "Britannia"}
    for acronym in acronyms:
...     original_text = acronyms[acronym].join(original_text.split(acronym))
... 
>>> original_text
... 'Go America\n Hail Britannia\n'

因此,不是一次性标记化和转换所有内容,而是为要替换和修改文档的每个首字母缩写对文档进行传递。当您完成每次修改后,您将输出最终结果。