簡體   English   中英

從文本文件中刪除特殊字符,但保留換行符(Python)

[英]Strip special characters from text file but keep new lines (Python)

我有一個文本文件,如下所示:

不能

慣於

不應該

我的目的是從文本文件中刪除所有特殊字符,同時保留每個單詞的新行。 輸出應如下所示:

不能

慣於

不應該

我當前正在使用以下代碼:

import re

class TextCleaner:
    uncleanText = open("words.txt").read()
    cleanText = re.sub('[^A-Za-z0-9]+', '', uncleanText)
    open('words.txt', 'w').write(cleanText)

但是,這將輸出以下內容:DontCantWontShouldnt

我可以在使用正則表達式保留新行的同時達到我的主要目標嗎?

您可以添加\\n保留新行,或添加\\s保留任何空白。 對於\\s來說就是這樣的代碼:

import re

class TextCleaner:
    uncleanText = open("words.txt").read()
    cleanText = re.sub('[^A-Za-z0-9\s]+', '', uncleanText)
    open('words.txt', 'w').write(cleanText)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM