[英]How to remove all lines with caps AND digits AND special characters AND all the lines longer than 10 characters from a text file in 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.