设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 6847|回复: 3
打印 上一主题 下一主题

How to delete the ½ in Python

[复制链接]

2

主题

0

好友

86

积分

注册会员

Rank: 2

跳转到指定楼层
楼主
发表于 2016-11-2 03:43:15 |只看该作者 |倒序浏览
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
回复

使用道具 举报

174

主题

45

好友

11万

积分

管理员

Rank: 9Rank: 9Rank: 9

沙发
发表于 2016-11-2 16:17:11 |只看该作者
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.
#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

2

主题

0

好友

86

积分

注册会员

Rank: 2

板凳
发表于 2016-11-2 20:53:30 |只看该作者
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')
万分感谢啊
回复

使用道具 举报

174

主题

45

好友

11万

积分

管理员

Rank: 9Rank: 9Rank: 9

地板
发表于 2016-11-2 22:05:09 |只看该作者
canadagoose 发表于 2016-11-2 20:53
你好,crossin先生,我是python菜鸟,有点没明白把那个utf8加到哪,能帮忙改下吗?以下是我代码,谢谢啦 ...

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


#==== Crossin的编程教室 ====#
微信ID:crossincode
网站:http://crossincode.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-9 04:39 , Processed in 0.017374 second(s), 23 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部