[英]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.