[英]Remove Weird Characters using python
我有一個很大的SQL文件,其中插入了大約1百萬個插入,其中一些插入已損壞(大約6000個),其中包含我需要刪除的奇怪字符,因此我可以將其插入到我的數據庫中。
例如:INSERT INTO BX-Books
VALUES('2268032019','Petite histoire de ladÃ?é©sinformation','Vladimir Volkoff',1999,'Roches du Rocher',' http: //images.amazon.com /images/P/2268032019.01.THUMBZZZ.jpg '' http://images.amazon.com/images/P/2268032019.01.MZZZZZZZ.jpg '' http://images.amazon.com/images/P/2268032019.01 .LZZZZZZZ.jpg ');
我只想刪除怪異的字符並保留所有正常字符
我嘗試使用以下代碼執行此操作:
import fileinput
import string
fileOld = open('text1.txt', 'r+')
file = open("newfile.txt", "w")
for line in fileOld: #in fileinput.input(['C:\Users\Vashista\Desktop\BX-SQL-Dump\test1.txt']):
print(line)
s = line
printable = set(string.printable)
filter(lambda x: x in printable, s)
print(s)
file.write(s)
但它似乎不起作用,當我打印s時,它與在行中打印的內容相同,更奇怪的是沒有任何內容寫入文件。
有關如何解決此問題的任何建議或技巧將很有用
import string
strg = "'2268032019', Petite histoire de la d�©sinformation','Vladimir Volkoff',1999,'Editions du Rocher','http://images.amazon.com/images/P/2268032019.01.THUMBZZZ.jpg','http://images.amazon.com/images/P/2268032019.01.MZZZZZZZ.jpg','http://images.amazon.com/images/P/2268032019.01.LZZZZZZZ.jpg');"
newstrg = ""
acc = """ '",{}[].`;: """
for x in strg:
if x in string.ascii_letters or x in string.digits or x in acc:
newstrg += x
print (newstrg)
輸出;
'2268032019', Petite histoire de la dsinformation','Vladimir Volkoff',1999,'Editions du Rocher','http:images.amazon.comimagesP2268032019.01.THUMBZZZ.jpg','http:images.amazon.comimagesP2268032019.01.MZZZZZZZ.jpg','http:images.amazon.comimagesP2268032019.01.LZZZZZZZ.jpg';
>>>
您可以檢查字符串的元素是否使用ASCII字母,然后創建一個不包含非ASCII字母的新字符串。
另外,它取決於您的變量類型。 如果使用列表,則不必定義新變量。 Just del mylist[x]
使用。
您可以使用正則表達式sub()進行簡單的字符串替換。 https://docs.python.org/2/library/re.html#re.sub
# -*- coding: utf-8 -*-
import re
dirty_string = u'©sinformation'
# in first param, put a regex to screen for, in this case I negated the desired characters.
clean_string = re.sub(r'[^a-zA-Z0-9./]', r'', dirty_string)
print clean_string
# Outputs
>>> sinformation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.