from docx import Document
alphaDic = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','!','?','.','~',',','(',')','$','-',':',';',"'",'/']
doc = Document('realexample.docx')
docIndex = 0
def delete_paragraph(paragraph):
p = paragraph._element
p.getparent().remove(p)
p._p = p._element = None
while docIndex < len(doc.paragraphs):
firstSen = doc.paragraphs[docIndex].text
rep_dic = {ord(k):None for k in alphaDic + [x.upper() for x in alphaDic]}
translation = (firstSen.translate(rep_dic))
removeExcessSpaces = " ".join(translation.split())
if removeExcessSpaces != '':
doc.paragraphs[docIndex].text = removeExcessSpaces
else:
delete_paragraph(doc.paragraphs[docIndex])
docIndex -=1 # go one step back in the loop because of the deleted index
docIndex +=1
所以測試文檔看起來像這樣的Python 3 - 如何去除只有特定的行空段落 - pythondocx
Hello
你好
Good afternoon
朋友們
Good evening
晚上好
而且我想下面來實現這一結果。
你好
朋友們
晚上好
現在代碼刪除所有空的段落和過多的空格,這樣做,所以我有點卡在這裏。我只想抹掉英文單詞造成的換行符。
你好
朋友們
晚上好
只需在if語句中添加另一個條件來檢查firstSen是否爲空然後它會將其寫入文件 – 2017-03-16 01:17:17
如果它是空的,那麼它會刪除段落在else語句中找到。循環遍歷所有段落,包括換行符(空段落),我不想刪除。 –
我建議你寫另一個條件,將第一個文件的空行寫入翻譯後的文件。所以你可以把'removeExcessSpaces!='':'改成'if removeExcessSpaces!=''或firstSen =='':'。這樣你就會說如果空行最初來自文件('firstSen =='''),那麼寫它(或它的翻譯,無所謂,因爲它們都是空的),就像它是其他文件一樣。 – 2017-03-16 20:26:21