Crossin的编程教室

标题: How to delete the ½ in Python [打印本页]

作者: canadagoose    时间: 2016-11-2 03:43
标题: How to delete the ½ in Python
I need to run one SQL file, but i have a below sentance in my SQL fiel: 13½ Elm Street. This ½ makes my SQL failed.
So i need to write the Python code to get rid of the symbol ½, my goal is to convert it to:      13 Elm Street.
the firs part of script that i wrote is :
                import os
                with open(r'D:\mysql_10.sql', 'r') as infile
                data = infile.read()
                data = data.replace('13½', "13")
                    data = data.replace("13½ Elm Street", "13 Elm Street")
                -----
Both of above replacement do not work, so i am wondering what's wrong with that. How could I delete that ½? Please help me to solve that problem.  

Thanks a lot

作者: crossin先生    时间: 2016-11-2 16:17
Two possible reasons
1. You read file, replaced ½, but not save it back or to another file.
2. ½ in file is saved by some charset, maybe it's not same as the charset of your code file. Make sure they are in same charset.
Add
  1. # coding: utf8
复制代码
or
  1. # coding: gbk
复制代码
to the first line of your code.
作者: canadagoose    时间: 2016-11-2 20:53
crossin先生 发表于 2016-11-2 16:17
Two possible reasons
1. You read file, replaced ½, but not save it back or to another file.
2. ½ i ...

你好,crossin先生,我是python菜鸟,有点没明白把那个utf8加到哪,能帮忙改下吗?以下是我代码,谢谢啦。
import os
with open(r'D:\OA\OAText\mysql_10.sql', 'r') as infile,open(r'D:\OA\OAText\mysql_N10.sql', 'w') as outfile:
    data = infile.read()
    data = data.replace("13½", "13")
    data = data.replace("½", "")
    data = data.replace("13½ Elm Street", "13 Elm Street")
   
    outfile.write(data)
    infile.close()
    outfile.close()
    os.remove('D:\OA\OAText\mysql_10.sql')
    os.rename(r'D:\OA\OAText\mysql_N10.sql',r'D:\OA\OAText\mysql_10.sql')
万分感谢啊
作者: crossin先生    时间: 2016-11-2 22:05
canadagoose 发表于 2016-11-2 20:53
你好,crossin先生,我是python菜鸟,有点没明白把那个utf8加到哪,能帮忙改下吗?以下是我代码,谢谢啦 ...

加到文件开头第一行,你看看其他帖子里的代码,或者网上搜一下,有非英文的都要这么加
至于是不是utf8,那就看你文件的实际保存格式了







欢迎光临 Crossin的编程教室 (https://bbs.crossincode.com/) Powered by Discuz! X2.5